Mathematica 9 is now available
 Documentation / Mathematica / The Mathematica Book / Practical Introduction / Functions and Programs  /

1.7.3 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 standard Mathematica iterator notation introduced for Sum and Product in Section 1.5.4.


Implementing repetitive operations.

  • This prints out the values of the first five factorials.
  • In[1]:= Do[ Print[i!], {i, 5} ]

    1

    2

    6

    24

    120

  • It is often more useful to have a list of results, which you can then manipulate further.
  • In[2]:= Table[ i!, {i, 5} ]

    Out[2]=

  • If you do not give an iteration variable, Mathematica simply repeats the operation you have specified, without changing anything.
  • In[3]:= r = 1; Do[ r = 1/(1 + r), {100} ]; r

    Out[3]=



    Any questions about topics on this page? Click here to get an individual response.Buy NowMore Information
    THIS IS DOCUMENTATION FOR AN OBSOLETE PRODUCT.
    SEE THE DOCUMENTATION CENTER FOR THE LATEST INFORMATION.