WolframLang: Loop

By Xah Lee. Date: . Last updated: .

Procedural Style Loop

Do-loop

The Do function syntax is same as Table. but it just return Null.

Do allows the use of Return, Break, Continue, Throw to return a alternative value and exit.

Do

Do[Print[2], 4]
(* print 2, 4 times *)
(* return Null *)
Do[Print[n], {n, 4}]
(* print 1 2 3 4 *)
(* nested loop, iterate over n, and m. *)
Do[Print[n,m], {n, 3}, {m, 2}]
(* 11 12 21 22 31 32 *) 
(* use a literal list of values. *)
Do[Print[i], {i, {1, 3, 20}}]
(* 1 3 20 *)

For-loop

For loop is basically never used in WolframLang, except in beginner code.

Use Do, Scan, Table, Map. See WolframLang: Iteration

For

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

While-loop

While loop is basically never used in WolframLang, except in beginner code.

While

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

WolframLang Loop, Iteration, Recursion