Skip to content
Programming contents

Lesson 1.5: Repeating: loops

If something repeats, you don't write it ten times. You write it once inside a loop.

The idea

A loop repeats instructions. You write them once and say how many times to repeat them, or until when.

For: a fixed number of times

Pseudocode
For i ← 1 To 5 Do
    Write i
EndFor
On screen
1
2
3
4
5

i is a variable the loop changes on its own: it starts at 1 and goes up by one until 5.

While: until something changes

Pseudocode
Algorithm Guess
    secret ← 7
    Write "Guess the number:"
    Read attempt
    While attempt ≠ secret Do
        Write "No. Try again:"
        Read attempt
    EndWhile
    Write "You got it!"
EndAlgorithm

Before each round it checks the condition. If it's true, it repeats; if it's false, it leaves the loop and carries on.

Use For when you know how many rounds you need, and While when you don't.

The infinite loop

If the condition never becomes false, the loop never ends:

Pseudocode
counter ← 1
While counter ≤ 5 Do
    Write counter
EndWhile

counter is always 1, so it repeats forever. It's missing counter ← counter + 1 inside.

The rule: inside a While, something has to move the condition towards false.

Try it

Exercise

Write the 3 times table, from 3 × 1 to 3 × 10.

Show the solution
Pseudocode
Algorithm TimesTable3
    For i ← 1 To 10 Do
        Write "3 x ", i, " = ", 3 * i
    EndFor
EndAlgorithm
On screen
3 x 1 = 3
3 x 2 = 6
…
3 x 10 = 30

Summary

  • A loop repeats instructions.
  • For: when you know how many times.
  • While: as long as a condition is true.
  • Inside a While, something has to make the condition false in the end.