Jump to content

Mathematica/FlowControl

From Wikibooks, open books for an open world

Control Flow

[edit | edit source]

If Statements

[edit | edit source]

For Loop

[edit | edit source]

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 | edit source]

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.