Skip to content
AgileLogics
5 min read

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 as Table.
  • In For[start, test, step, body] and While[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}
  • Table collects results instead of printing them.
  • Sum and Product work symbolically too: Sum[k, {k, n}] gives 1/2 n (1 + n).
  • NestList[f, x, n] applies f repeatedly and keeps every step.

Common mistakes

  • Commas instead of semicolons inside a loop body: Do[a = i, Print[a], {i, 3}] passes Print[a] as the iterator and fails. Write Do[a = i; Print[a], {i, 3}].
  • Building a list with AppendTo inside a loop — it copies the list each time and gets slow for large data. Use Table instead.

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.