Iteration means repeating a block of instructions. Instead of writing the same code 100 times, a loop does it for you. This lesson covers the three common loop types and when to pick each.

Count-controlled loops (for)

Use a for loop when you know in advance how many times to repeat. In IB-style pseudocode:

loop I from 1 to 5
   output I
end loop

This outputs 1, 2, 3, 4, 5. The loop variable I is set up, tested and increased automatically. In Python this is for i in range(1, 6):, and in Java for (int i = 1; i <= 5; i++).

Example: adding up the numbers 1 to 100.

total = 0
loop I from 1 to 100
   total = total + I
end loop
output total      // 5050

Condition-controlled loops (while)

A while loop repeats as long as a condition is true. The condition is tested before each pass, so the body may run zero times.

loop while balance > 0
   balance = balance - payment
end loop

Use it when you do not know how many repetitions are needed, such as reading until the user types “quit”.

input word
loop while word != "quit"
   output word
   input word
end loop

Danger: if the condition never becomes false, the result is an infinite loop. Always make sure something inside the loop moves it towards ending.

do-while loops

A do-while (or repeat-until) loop tests the condition after each pass, so the body always runs at least once. This suits input validation:

do
   input age
while age < 0 or age > 120

The user is asked once, and again only if the value is invalid. In pseudocode this is also written loop ... until condition, where the loop ends when the condition becomes true.

Choosing a loop

  • Known number of repeats: for.
  • Unknown repeats, may need zero: while.
  • Unknown repeats, must run at least once: do-while.

Nested loops

A loop inside another repeats the inner loop completely for each pass of the outer. A multiplication table uses two:

loop R from 1 to 3
   loop C from 1 to 3
      output R * C
   end loop
end loop

This runs the inner body 3 x 3 = 9 times.

Common errors

  • Off-by-one: looping one time too many or too few. Check start and end values.
  • Forgetting to update the condition variable.
  • Changing the loop counter inside a for loop, which causes unpredictable behaviour.

Check your understanding

Which loop is best when the number of repetitions is known?

  • for
  • while
  • do-while
  • case

Answer: for. The counter controls the repetitions.

What is special about a do-while loop?

  • The body runs at least once
  • It never runs
  • It always runs forever
  • It only works with strings

Answer: The body runs at least once. The condition is tested after the body.

How many times does the body of loop I from 1 to 4 run?

  • 3
  • 4
  • 5
  • 0

Answer: 4. It runs for I = 1, 2, 3 and 4.

What is an infinite loop?

  • A loop whose condition never becomes false
  • A loop with one pass
  • A nested loop
  • A loop in a function

Answer: A loop whose condition never becomes false. The program never moves on.