WolframLang: Loop and Iteration

By Xah Lee. Date: . Last updated: .

Procedural Style Loop

WolframLang is a function language. However, it supports the traditional loops constructs such as for-loop, while-loop, do-loop. In general, you should not use them, because they are slower and more complex.

For-loop

For

For[i = 1, i < 9, i++, Print[i]]

While-loop

While

n = 1; While[n < 4, Print[n]; n++]

Do-loop

The Do function is similar to Table [see WolframLang: Create List] , except it doesn't generate a list, it just return Null (if there is no Return), and you can use Return, Break, Continue, and Throw inside Do.

Do[expr, n]
evaluate expr n times.
Do[expr,{i, iMax}]
evaluate expr with the variable i successively taking on the values 1 through iMax (in steps of 1).
Do[expr,{i, iMin, iMax}]
start with iMin.
Do[expr,{i, iMin, iMax, di}]
use steps di.
Do[expr,{i, iMin, iMax, di}, {j, jMin, jMax, dj} etc]
Nested do-loop. For each i, loop over j, etc.
Do[expr,{i,{i1, i2, i3 etc}}}]
use the successive values i.

Example:

Do[Print[n^2], {n, 4}]
(* 1 4 9 16 *)
Do[Print[n,m], {n, 4}, {m, 2}]
(* 11 12 21 22 31 32 41 42 *)

WolframLang Loop, Iteration, Recursion

WolframLang in Depth

Basics

Comment, Print

String

Arithmetic

List

Expression, Atom, Head

Boolean

Conditional

Variable

Loop

Data Structure

Function

Pattern Matching

Advanced

Shell Tasks

Misc