Group Abstract Group Abstract

Message Boards Message Boards

0
|
24.5K Views
|
4 Replies
|
8 Total Likes
View groups...
Share
Share this post:

How to use do, for, while loops?

Posted 11 years ago
POSTED BY: Alice Bishop
4 Replies

And a good book to work your way though is the following:

http://www.amazon.com/Programming-Mathematica-Introduction-Paul-Wellin/dp/1107009464/

I think that Szabolcs would agree with me that the next important step for you would be to spend time learning (by working through a course like this book or the on-line course that he pointed you to) how to program in Mathematica--and essential to this is to work many examples. Good luck!

POSTED BY: David Reiss
POSTED BY: Szabolcs Horvát
Posted 11 years ago

Hi Alice,

Daniel is of course correct, and perhaps has better sense than I do in that he gave you a direct answer to your question. But I would also like to point out that Mathematica offers a significantly different paradigm in programming compared to mainly procedural languages like C. It does of course have Do, For, and While -- and these are still useful in some calculations, especially where results are built up in an iteration, like you are doing calculating N factorial.

But I usually call Mathematica a 10th generation language. (I started calling it that somewhere around V4, so maybe I should increment that!) As an example, below are a few more ways to calculate N Factorial.

Kind regards and enjoy Mathematica,

David

In[1]:= (* by recursion *)
fact1[1] = 1;

In[2]:= fact1[n_] := n fact1[n - 1];

In[3]:= fact1[3]

Out[3]= 6

In[4]:= (* by Apply *)
fact2[n_] := Times @@ Range[1, n]

In[5]:= fact2[3]

Out[5]= 6

In[6]:= (* and of course by built in *)
Factorial[3]

Out[6]= 6

In[7]:= (* or *)
3!

Out[7]= 6
POSTED BY: David Keith

(1) The inner While will run forever. Nothing inside it changes the condition to False.

(2) Mathematica is case sensitive. So you'd want Print where you have print.

(3) You are working too hard (I don't mean just from a Mathematica perspective, but from that of programming in general). Calculating 10! in this way should require a single loop in any language, not two (let alone three, which is what you have). You could for example start with n=1 and, at each step, change it via n=n*I.

POSTED BY: Daniel Lichtblau
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard