Loops and Iteration
Prerequisites: Logic and conditionals
The Wolfram Language has loops, but you'll use them less than in other
languages: Table, listable arithmetic, and functions like Sum usually
do the job more clearly.
Do, For, While
Do[Print[i^2], {i, 3}]
1
4
9
For[i = 1, i <= 3, i++, Print["step ", i]]
step 1
step 2
step 3
n = 1;
While[n < 100, n = 2 n];
n
128
Do[body, {i, n}]uses the same iterator syntax asTable.- In
For[start, test, step, body]andWhile[test, body], separate statements inside the body with;. - Loops return nothing useful (
Null), so they work through side effects — printing or changing variables.
The same work without loops
Table[i^2, {i, 3}]
Sum[i, {i, 100}]
Product[i, {i, 5}]
NestList[Sqrt, 256, 3]
{1, 4, 9}
5050
120
{256, 16, 4, 2}
Tablecollects results instead of printing them.SumandProductwork symbolically too:Sum[k, {k, n}]gives1/2 n (1 + n).NestList[f, x, n]appliesfrepeatedly and keeps every step.
Common mistakes
- Commas instead of semicolons inside a loop body:
Do[a = i, Print[a], {i, 3}]passesPrint[a]as the iterator and fails. WriteDo[a = i; Print[a], {i, 3}]. - Building a list with
AppendToinside a loop — it copies the list each time and gets slow for large data. UseTableinstead.
Practice
Find the smallest power of 3 greater than 1,000,000 with a While loop,
then do it again without a loop.
Show solution
p = 1;
While[p <= 1000000, p = 3 p];
p
3^Ceiling[Log[3, 1000000]]
1594323
1594323
3^12 = 531441 and 3^13 = 1594323.