Mathematica/FlowControl

Control Flow

edit

If Statements

edit

For Loop

edit

For[start, test, incr, body] executes start, then repeatedly evaluates body and incr until test fails to give True.

Example:

For[x=1, x<5, x=x+1, Print["x=",x]]

While Loop

edit

While[test, body] evaluates test, then body, repetitively, until test first fails to give True.

Example:
Define a Function f[x]

f[x_] := (x^2 -1)/(x+1)

Use the function in a while loop to calculate the sum of those terms.

i=0; While[i < 0, tot += f[i]; i++].

Note that the roles of ; and , are reversed relative to the C programming language.