Topic 8 · Programming
Iteration with FOR, WHILE, and REPEAT
Count-controlled, pre-condition, and post-condition loops, when to use each one, and how to avoid endless loops.
Three kinds of loop
Iteration repeats a block of statements. Pick the loop by what you know before it starts:
| Loop | Type | Use when | Runs at least once? |
|---|---|---|---|
FOR ... NEXT | Count-controlled | You know how many times to repeat | Depends on the range |
WHILE ... ENDWHILE | Pre-condition | You repeat while a condition is TRUE, checked before each run | No: may run zero times |
REPEAT ... UNTIL | Post-condition | You repeat until a condition is TRUE, checked after each run | Yes |
FOR loops
A FOR loop gives a counter variable each value from a start to an end. Add STEP to count in different jumps, including backwards.
DECLARE Count : INTEGER
FOR Count <- 1 TO 5
OUTPUT Count * Count
NEXT Count| Count | OUTPUT |
|---|---|
| 1 | 1 |
| 2 | 4 |
| 3 | 9 |
| 4 | 16 |
| 5 | 25 |
Counting backwards with STEP
DECLARE Seconds : INTEGER
FOR Seconds <- 10 TO 0 STEP -2
OUTPUT Seconds
NEXT Seconds
OUTPUT "Lift off!"WHILE loops
A WHILE loop checks its condition first. If the condition is FALSE at the start, the body never runs. Use it when you might not need to repeat at all.
DECLARE Balance : REAL
DECLARE Years : INTEGER
Balance <- 100
Years <- 0
WHILE Balance < 200 DO
Balance <- Balance * 1.05
Years <- Years + 1
ENDWHILE
OUTPUT "Doubled after ", Years, " years"REPEAT ... UNTIL loops
A REPEAT loop runs its body first and checks the condition afterwards, so it always runs at least once. This is perfect for asking for input, because you have to ask before you can check.
DECLARE Guess : INTEGER
REPEAT
OUTPUT "Guess the number"
INPUT Guess
UNTIL Guess = 7
OUTPUT "Correct!"Watch out. A condition loop must change something its condition depends on. If nothing inside the loop can make the condition change, the loop never ends.
Nested loops
A loop inside a loop runs the inner loop completely for every pass of the outer loop. This prints a times table grid.
DECLARE Row : INTEGER
DECLARE Column : INTEGER
FOR Row <- 1 TO 3
FOR Column <- 1 TO 3
OUTPUT Row, " x ", Column, " = ", Row * Column
NEXT Column
NEXT RowKey terms
- Iteration
- Repeating a set of statements.
- Count-controlled loop
- A loop that repeats a set number of times (FOR).
- Pre-condition loop
- A loop that checks its condition before each run (WHILE).
- Post-condition loop
- A loop that checks its condition after each run (REPEAT ... UNTIL).
Check yourself
Which loop should ask for a password until it is correct?Show answer
REPEAT ... UNTIL: the password must be asked for at least once before it can be checked.
How many times does the inner statement run in the nested loop example?Show answer
3 × 3 = 9 times.
What is output by FOR I <- 2 TO 10 STEP 4?Show answer
2, 6, 10.
Practise this skill
Use what you learned in a question, then run your answer in the studio editor.