Loops and Control Structures

The execution of a Wolfram Language program involves the evaluation of a sequence of Wolfram Language 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 1 to imax in steps of 1
Do[expr,{i,imin,imax,di}]evaluate expr with i varying from imin to imax 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[i^2], with i running from 1 to 4:
Click for copyable input
This executes an assignment for t in a loop with k running from 2 to 6 in steps of 2:
Click for copyable input

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 i from 1 to 4, and for each value of i, loops over j from 1 to i-1:
Click for copyable input

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 t=1/(1+t) three times:
Click for copyable input
You can put a procedure inside Do:
Click for copyable input
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[f,x,n], for example, allows you to apply a function repeatedly to an expression.

This nests f three times:
Click for copyable input
By nesting a pure function, you can get the same result as in the example with Do above:
Click for copyable input

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[f,x].

FixedPoint goes on applying a function until the result no longer changes:
Click for copyable input

You can use FixedPoint to imitate the evaluation process in the Wolfram Language, or the operation of functions such as expr//.rules. 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[value,tag] is encountered, where form matches tag
Catch[expr,form,f]return f[value,tag] instead of value

Nonlocal control of evaluation.

When the Throw is encountered, evaluation stops, and the current value of i is returned as the value of the enclosing Catch:
Click for copyable input

Throw and Catch provide a flexible way to control the process of evaluation in the Wolfram Language. The basic idea is that whenever a Throw is encountered, the evaluation that is then being done is stopped, and the Wolfram Language 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:
Click for copyable input
The evaluation of Scan stops as soon as Throw is encountered, and the enclosing Catch returns as its value the argument of Throw:
Click for copyable input
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:
Click for copyable input

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:
Click for copyable input
Since there is no Throw encountered, the result here is just as before:
Click for copyable input
Now the evaluation of the NestList is diverted, and the single number given as the argument of Throw is returned:
Click for copyable input

Throw and Catch operate in a completely global way: it does not matter how or where a Throw is generatedit will always stop evaluation and return to the enclosing Catch.

The Throw stops the evaluation of f, and causes the Catch to return just a, with no trace of f left:
Click for copyable input
This defines a function which generates a Throw when its argument is larger than 10:
Click for copyable input
No Throw is generated here:
Click for copyable input
But here the Throw generated inside the evaluation of g returns to the enclosing Catch:
Click for copyable input

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[value,tag] and Catch[expr,form]. 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.

Here the Throw is caught by the inner Catch:
Click for copyable input
But here it is caught only by the outer Catch:
Click for copyable input
You can use patterns in specifying the tags which a particular Catch should catch:
Click for copyable input
This keeps the tag a completely local:
Click for copyable input

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:
Click for copyable input

When you use Catch[expr,form] with Throw[value,tag], the value returned by Catch is simply the expression value given in the Throw. If you use Catch[expr,form,f], however, then the value returned by Catch is instead f[value,tag].

Here f is applied to the value and tag in the Throw:
Click for copyable input
If there is no Throw, f is never used:
Click for copyable input
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 Wolfram Language 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:
Click for copyable input

The functions While and For in the Wolfram Language are similar to the control structures while and for 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 Wolfram Language For loops relative to C language ones.

This is a very common form for a For loop. i++ increments the value of i:
Click for copyable input
Here is a more complicated For loop. Notice that the loop terminates as soon as the test i^2<10 fails:
Click for copyable input

In the Wolfram Language, 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:
Click for copyable input

In a While or For loop, or in general in any Wolfram Language procedure, the Wolfram Language 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 Wolfram Language program.

In most cases, you should try to keep the flow of control in your Wolfram Language 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 Wolfram Language 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 the Wolfram Language 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 from 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 t exceeds 19:
Click for copyable input
When k<3, the Continue[] causes the loop to be continued, without executing t+=2:
Click for copyable input

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:
Click for copyable input
When the argument is greater than 5, the first Return in the procedure is used:
Click for copyable input
This function "throws" error if its argument is negative:
Click for copyable input
No Throw is generated here:
Click for copyable input
But in this case a Throw is generated, and the whole Catch returns the value error:
Click for copyable input

Functions like Continue[] and Break[] allow you to "transfer control" to the beginning or end of a loop in a Wolfram Language program. Sometimes you may instead need to transfer control to a particular element in a Wolfram Language 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 q exceeds 6:
Click for copyable input

Note that you can use Goto in a particular Wolfram Language procedure only when the Label it specifies occurs as an element of the same Wolfram Language 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.