Repetitive Operations

In using Mathematica, you sometimes need to repeat an operation many times. There are many ways to do this. Often the most natural is in fact to set up a structure such as a list with many elements, and then apply your operation to each of the elements.

Another approach is to use the Mathematica function Do, which works much like the iteration constructs in languages such as C and Fortran. Do uses the same Mathematica iterator notation as Sum and Product, described in "Sums and Products".

Do[expr,{i,imax}]evaluate expr with i running from 1 to
Do[expr,{i,imin,imax,di}]evaluate expr with i running from to in steps of di
Print[expr]print expr
Table[expr,{i,imax}]make a list of the values of expr with i running from 1 to

Implementing repetitive operations.

This prints out the values of the first five factorials.
It is often more useful to have a list of results, which you can then manipulate further.
In[2]:=
Click for copyable input
Out[2]=
If you do not give an iteration variable, Mathematica simply repeats the operation you have specified, without changing anything.
In[3]:=
Click for copyable input
Out[3]=
New to Mathematica? Find your learning path »
Have a question? Ask support »