WolframLang: Loop
Procedural Style Loop
WolframLang is a function language. However, it supports the traditional loop constructs such as for-loop, while-loop. In general, you should not use them, because they are slower and more complex.
If you need to exit by condition or with side-effects, use Do
, Scan
.
Else, use functional programing to maintain structure.
See
• Create List (Table)
• Map, Scan
• Recursion
Do-loop
The Do
function is similar to
Table
[see WolframLang: Create List (Table, Range)]
, 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[Print[2], 4]
Do[expr, {i, iMax}]
- evaluate expr with the variable i successively taking on the values 1 through iMax (in steps of 1).
Do[Print[n^2], {n, 4}] (* 1 4 9 16 *)
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[Print[n,m], {n, 3}, {m, 2}] (* 11 12 21 22 31 32 *)
Do[expr, {i, {i1, i2, i3 etc}}}]
- use the successive values i.
Do[Print[i], {i, {1, 3, 20}}] (* 1 3 20 *)
For-loop
For
loop is basically never used in WolframLang, except in beginner code.
For[i = 1, i < 9, i++, Print[i]]
While-loop
While
loop is basically never used in WolframLang, except in beginner code.
n = 1; While[n < 4, Print[n]; n++]