Loops and Control Structures
The execution of a
Mathematica program involves the evaluation of a sequence of
Mathematica expressions. In simple programs, the expressions to be evaluated may be separated by semicolons, and evaluated one after another. Often, however, you need to evaluate expressions several times, in some kind of "loop".
| Do[expr,{i,imax}] | evaluate expr repetitively, with i varying from to in steps of  |
| Do[expr,{i,imin,imax,di}] | evaluate expr with i varying from to in steps of di |
| Do[expr,{i,list}] | evaluate expr with i taking on values from list |
| Do[expr,{n}] | evaluate expr n times |
Simple looping constructs.
This evaluates
Print
, with

running from

to

.
This executes an assignment for

in a loop with

running from

to

in steps of

.
| Out[2]= |  |
The way iteration is specified in
Do is exactly the same as in functions like
Table and
Sum. Just as in those functions, you can set up several nested loops by giving a sequence of iteration specifications to
Do.
This loops over values of

from

to

, and for each value of

, loops over

from

to

.
Sometimes you may want to repeat a particular operation a certain number of times, without changing the value of an iteration variable. You can specify this kind of repetition in
Do just as you can in
Table and other iteration functions.
This repeats the assignment

three times.
| Out[4]= |  |
You can put a procedure inside
Do.
| Nest[f,expr,n] | apply f to expr n times |
| FixedPoint[f,expr] | start with expr, and apply f repeatedly until the result no longer changes |
| NestWhile[f,expr,test] | start with expr, and apply f repeatedly until applying test to the result no longer yields True |
Applying functions repetitively.
Do allows you to repeat operations by evaluating a particular expression many times with different values for iteration variables. Often, however, you can make more elegant and efficient programs using the functional programming constructs discussed in
"Applying Functions Repeatedly".
Nest
, for example, allows you to apply a function repeatedly to an expression.
This nests

three times.
| Out[6]= |  |
By nesting a pure function, you can get the same result as in the example with
Do above.
| Out[7]= |  |
Nest allows you to apply a function a specified number of times. Sometimes, however, you may simply want to go on applying a function until the results you get no longer change. You can do this using
FixedPoint
.
FixedPoint goes on applying a function until the result no longer changes.
| Out[8]= |  |
You can use
FixedPoint to imitate the evaluation process in
Mathematica, or the operation of functions such as

.
FixedPoint goes on until two successive results it gets are the same.
NestWhile allows you to go on until an arbitrary function no longer yields
True.
| Catch[expr] | evaluate expr until Throw[value] is encountered, then return value |
| Catch[expr,form] | evaluate expr until Throw is encountered, where form matches tag |
| Catch[expr,form,f] | return instead of value |
Nonlocal control of evaluation.
When the
Throw is encountered, evaluation stops, and the current value of

is returned as the value of the enclosing
Catch.
| Out[9]= |  |
Throw and
Catch provide a flexible way to control the process of evaluation in
Mathematica. The basic idea is that whenever a
Throw is encountered, the evaluation that is then being done is stopped, and
Mathematica immediately returns to the nearest appropriate enclosing
Catch.
Scan applies the function
Print to each successive element in the list, and in the end just returns
Null.
The evaluation of
Scan stops as soon as
Throw is encountered, and the enclosing
Catch returns as its value the argument of
Throw.
| Out[11]= |  |
The same result is obtained with
Map, even though
Map would have returned a list if its evaluation had not been stopped by encountering a
Throw.
| Out[12]= |  |
You can use
Throw and
Catch to divert the operation of functional programming constructs, allowing for example the evaluation of such constructs to continue only until some condition has been met. Note that if you stop evaluation using
Throw, then the structure of the result you get may be quite different from what you would have got if you had allowed the evaluation to complete.
Here is a list generated by repeated application of a function.
| Out[13]= |  |
Since there is no
Throw encountered, the result here is just as before.
| Out[14]= |  |
Now the evaluation of the
NestList is diverted, and the single number given as the argument of
Throw is returned.
| Out[15]= |  |
Throw and
Catch operate in a completely global way: it does not matter how or where a
Throw is generated—it will always stop evaluation and return to the enclosing
Catch.
The
Throw stops the evaluation of

, and causes the
Catch to return just

, with no trace of

left.
| Out[16]= |  |
This defines a function which generates a
Throw when its argument is larger than 10.
No
Throw is generated here.
| Out[18]= |  |
But here the
Throw generated inside the evaluation of

returns to the enclosing
Catch.
| Out[19]= |  |
In small programs, it is often adequate to use
Throw[value] and
Catch[expr] in their simplest forms. But particularly if you write larger programs that contain many separate pieces, it is usually much better to use
Throw
and
Catch
. By keeping the expressions
tag and
form local to a particular piece of your program, you can then ensure that your
Throw and
Catch will also operate only within that piece.
| Out[20]= |  |
But here it is caught only by the outer
Catch.
| Out[21]= |  |
You can use patterns in specifying the tags which a particular
Catch should catch.
| Out[22]= |  |
This keeps the tag

completely local.
| Out[23]= |  |
You should realize that there is no need for the tag that appears in
Throw to be a constant; in general it can be any expression.
Here the inner
Catch catches all throws with tags less than 4, and continues the
Do. But as soon as the tag reaches 4, the outer
Catch is needed.
| Out[24]= |  |
When you use
Catch
with
Throw
, the value returned by
Catch is simply the expression
value given in the
Throw. If you use
Catch
, however, then the value returned by
Catch is instead

.
Here

is applied to the value and tag in the
Throw.
| Out[25]= |  |
If there is no
Throw,

is never used.
| Out[26]= |  |
| While[test,body] | evaluate body repetitively, so long as test is True |
| For[start,test,incr,body] | evaluate start, then repetitively evaluate body and incr, until test fails |
General loop constructs.
Functions like
Do,
Nest, and
FixedPoint provide structured ways to make loops in
Mathematica programs, while
Throw and
Catch provide opportunities for modifying this structure. Sometimes, however, you may want to create loops that even from the outset have less structure. And in such cases, you may find it convenient to use the functions
While and
For, which perform operations repeatedly, stopping when a specified condition fails to be true.
The
While loop continues until the condition fails.
The functions
While and
For in
Mathematica are similar to the control structures

and

in languages such as C. Notice, however, that there are a number of important differences. For example, the roles of comma and semicolon are reversed in
Mathematica For loops relative to C language ones.
This is a very common form for a
For loop.

increments the value of

.
Here is a more complicated
For loop. Notice that the loop terminates as soon as the test

fails.
In
Mathematica, both
While and
For always evaluate the loop test before evaluating the body of the loop. As soon as the loop test fails to be
True,
While and
For terminate. The body of the loop is thus only evaluated in situations where the loop test is
True.
The loop test fails immediately, so the body of the loop is never evaluated.
In a
While or
For loop, or in general in any
Mathematica procedure, the
Mathematica expressions you give are evaluated in a definite sequence. You can think of this sequence as defining the "flow of control" in the execution of a
Mathematica program.
In most cases, you should try to keep the flow of control in your
Mathematica programs as simple as possible. The more the flow of control depends for example on specific values generated during the execution of the program, the more difficult you will typically find it to understand the structure and operation of the program.
Functional programming constructs typically involve very simple flow of control.
While and
For loops are always more complicated, since they are set up to make the flow of control depend on the values of the expressions given as tests. Nevertheless, even in such loops, the flow of control does not usually depend on the values of expressions given in the body of the loop.
In some cases, however, you may need to construct
Mathematica programs in which the flow of control is affected by values generated during the execution of a procedure or of the body of a loop. One way to do this, which fits in with functional programming ideas, is to use
Throw and
Catch. But
Mathematica also provides various functions for modifying the flow of control which work like in languages such as C.
| Break[] | exit the nearest enclosing loop |
| Continue[] | go to the next step in the current loop |
| Return[expr] | return the value expr, exiting all procedures and loops in a function |
| Goto[name] | go to the element Label[name] in the current procedure |
| Throw[value] | return value as the value of the nearest enclosing Catch (nonlocal return) |
Control flow functions.
The
Break
causes the loop to terminate as soon as

exceeds

.
When

, the
Continue
causes the loop to be continued, without executing

.
Return[expr] allows you to exit a particular function, returning a value. You can think of
Throw as a kind of nonlocal return which allows you to exit a whole sequence of nested functions. Such behavior can be convenient for handling certain error conditions.
Here is an example of the use of
Return. This particular procedure could equally well have been written without using
Return.
When the argument is greater than 5, the first
Return in the procedure is used.
| Out[34]= |  |
This function "throws"

if its argument is negative.
No
Throw is generated here.
| Out[36]= |  |
But in this case a
Throw is generated, and the whole
Catch returns the value

.
| Out[37]= |  |
Functions like
Continue
and
Break
allow you to "transfer control" to the beginning or end of a loop in a
Mathematica program. Sometimes you may instead need to transfer control to a particular element in a
Mathematica procedure. If you give a
Label as an element in a procedure, you can use
Goto to transfer control to this element.
This goes on looping until

exceeds

.
Note that you can use
Goto in a particular
Mathematica procedure only when the
Label it specifies occurs as an element of the same
Mathematica procedure. In general, use of
Goto reduces the degree of structure that can readily be perceived in a program, and therefore makes the operation of the program more difficult to understand.