Study Guide
Iteration
How a program repeats instructions: count-controlled FOR loops (with STEP), pre-condition WHILE loops and post-condition REPEAT loops, how to choose between them, and loops nested inside loops.
Lesson 5.5 Algorithms and Programming
For: Cambridge IGCSE Computer Science learners, or Key Stage 3 learners who have met variables, operators and selection (about ages 13 to 14)
Stage: Think
A countdown
A fictional game, Rocket Rescue, shows a countdown before the rocket launches: 10, 9, 8, and so on down to 1, then “Blast off!”. A beginner writes ten OUTPUT lines, one for each number.
Think it through
The designers now want a countdown from 1000. What is wrong with writing one OUTPUT line for each number, and what would you want a programming language to let you say instead?
- Hint 1: How long would the program be? What happens if the countdown must change?
Show a model answer
The program would be a thousand lines long, tiring to write and easy to get wrong, and it would have to be rewritten for every different countdown. It would be much better to be able to say “repeat this one instruction, once for each number from 1000 down to 1”. Repeating instructions is called iteration, and the repeated block is a loop.
Stage: Predict
Repeating a set number of times
Iteration means repeating instructions, and a loop is the block of instructions that is repeated. If the number of repeats is known before the loop starts, a count-controlled loop is used. In pseudocode it is a FOR … NEXT loop:
FOR Count ← 1 TO 5
OUTPUT Count * 2
NEXT CountThink it through
Predict what this program outputs, in order. How many times does the OUTPUT line run, and what does the variable Count hold each time?
- Hint 1: Count starts at 1. What does it hold on the next pass?
Show a model answer
The OUTPUT line runs five times, with Count holding 1, 2, 3, 4 and 5, so the output is 2, 4, 6, 8, 10 (one number on each line). Count changes by itself, one step each time round, until it has passed 5.
In FOR Count ← 1 TO 5, the variable Count is set to 1, the lines down to NEXT Count are carried out, then Count goes up by 1 automatically and they are carried out again, until Count has taken every value from 1 to 5. Both ends are included. Follow the loop in a trace table:
| Pass | Count | OUTPUT |
|---|---|---|
| 1 | 1 | |
| 2 | ||
| 3 | ||
| 4 | ||
| 5 |
Show the completed table
| Pass | Count | OUTPUT |
|---|---|---|
| 1 | 1 | 2 |
| 2 | 2 | 4 |
| 3 | 3 | 6 |
| 4 | 4 | 8 |
| 5 | 5 | 10 |
The loop changes Count for you: NEXT Count does the adding. Do not write Count ← Count + 1 inside a FOR loop, and do not change Count in the loop body.
Check your understanding
Show the answer
Answer: B. 6, because Count takes the values 4, 5, 6, 7, 8 and 9.
The number of passes is the last value minus the first, plus 1.
A loop can count in bigger jumps, or downwards, by adding STEP. The step can be negative:
FOR Number ← 10 TO 0 STEP -5
OUTPUT Number
NEXT NumberIf the start is already past the end, the loop body never runs: FOR Count ← 5 TO 1 with the usual step of +1 runs zero times, because Count is already past 1.
Check your understanding
Show the answer
Answer: C. 10, 5 and 0, each on its own line.
STEP sets the jump; the end value is included if the steps land on it.
Stage: Discover
Repeating while something is true
Sometimes the number of repeats is not known in advance. A fictional drinks machine sells a drink for 2 coins, and a pupil puts in 7 coins. The machine keeps selling drinks for as long as the pupil has enough coins.
Think it through
How many drinks does the pupil get, and how many coins are left? Describe how you worked it out, and say whether you knew in advance how many times you would repeat the step.
- Hint 1: Take 2 coins away, and give a drink. When do you stop?
Show a model answer
3 drinks and 1 coin left. Take away 2 coins and give a drink: 7 becomes 5, then 3, then 1. At 1 coin there is not enough for another drink, so you stop. You did not know in advance how many times you would repeat; you kept going while there were at least 2 coins.
A pre-condition loop tests its condition before each pass and repeats while it is true. In pseudocode it is WHILE … DO … ENDWHILE:
Coins ← 7
Drinks ← 0
WHILE Coins >= 2 DO
Coins ← Coins - 2
Drinks ← Drinks + 1
ENDWHILE
OUTPUT Drinks, " drinks, ", Coins, " coin left"Because the test comes first, it is made before every pass, including the first. Trace this program. Each row shows the situation just before the condition is tested.
| Moment | Coins | Drinks | Coins >= 2? | OUTPUT |
|---|---|---|---|---|
| Before the first pass | 7 | 0 | ||
| After pass 1 | ||||
| After pass 2 | ||||
| After pass 3 | ||||
| After the loop | 1 | 3 |
Show the completed table
| Moment | Coins | Drinks | Coins >= 2? | OUTPUT |
|---|---|---|---|---|
| Before the first pass | 7 | 0 | Yes | |
| After pass 1 | 5 | 1 | Yes | |
| After pass 2 | 3 | 2 | Yes | |
| After pass 3 | 1 | 3 | No | |
| After the loop | 1 | 3 | 3 drinks, 1 coin left |
Check your understanding
Show the answer
Answer: A. Zero times, because the test is false before the first pass.
A pre-condition loop can run zero times: with 1 coin the test Coins >= 2 is false at once, the loop is skipped and the output is “0 drinks, 1 coin left”.
Apply it
Show the answer
Answer: A. The body never changes Coins, so the condition stays true forever.
A loop whose condition can never become false is called an infinite loop.
Stage: Discover
Repeating until something is true
A fictional school computer asks for a password. It must ask at least once, and keep asking until the right one is typed.
Think it through
Could a WHILE loop do this without any extra work? Think about what the test would have to look at before the first password has been typed.
- Hint 1: A WHILE loop tests first. Has the user typed anything yet at that point?
Show a model answer
Not directly. A WHILE loop tests before its first pass, and before the first pass nothing has been typed, so the program would need a first INPUT outside the loop (or a starting value that makes the test true). A loop that carries out its body first and tests afterwards fits the job better.
A post-condition loop carries out its body first and tests afterwards, so it always runs at least once. In pseudocode it is REPEAT … UNTIL:
REPEAT
OUTPUT "Enter the password"
INPUT Password
UNTIL Password = "Secret"
OUTPUT "Welcome"The condition after UNTIL says when to stop: the loop repeats until it is true. A user types abc and then Secret. Follow the program:
| Pass | Password typed | Password = "Secret"? | OUTPUT during the pass |
|---|---|---|---|
| 1 | abc | ||
| 2 | Secret | ||
| After the loop |
Show the completed table
| Pass | Password typed | Password = "Secret"? | OUTPUT during the pass |
|---|---|---|---|
| 1 | abc | No | Enter the password |
| 2 | Secret | Yes | Enter the password |
| After the loop | Welcome |
Do not confuse: WHILE and REPEAT
- When is the test?WHILE … DO … ENDWHILE
- Before each pass, so the body may run zero times. The condition says when to carry on.WHILE Coins >= 2 DO …
- When is the test?REPEAT … UNTIL
- After each pass, so the body always runs at least once. The condition says when to stop.UNTIL Password = "Secret"
The condition is the opposite way round. To turn a WHILE condition into the matching UNTIL condition, ask when the loop should stop.
Check your understanding
Show the answer
Answer: B. UNTIL stops when its condition is true, and Password <> “Secret” is true for a wrong one.
For REPEAT, write the condition that means “we are finished”.
Stage: Apply
Choosing the right loop
Each of the three loops suits a different kind of job. Decide which one is best for each task below. Answer FOR, WHILE or REPEAT.
| Task | Best loop |
|---|---|
| Output every whole number from 1 to 100 | |
| Keep asking for a PIN until the right one is typed (it must be asked at least once) | |
| Subtract 5 from a balance while the balance is at least 5 (the balance might already be too low) | |
| Draw a row of 20 stars |
- FOR when the count is known; WHILE when the body may not run at all; REPEAT when it must run at least once.
Show the completed table
| Task | Best loop |
|---|---|
| Output every whole number from 1 to 100 | FOR |
| Keep asking for a PIN until the right one is typed (it must be asked at least once) | REPEAT |
| Subtract 5 from a balance while the balance is at least 5 (the balance might already be too low) | WHILE |
| Draw a row of 20 stars | FOR |
Apply it
Show the answer
Answer: C. REPEAT … UNTIL Age >= 1 AND Age <= 120, so it asks once and stops on a valid age.
REPEAT fits input checking: ask first, then test.
Stage: Predict
Loops inside loops
A loop can contain another loop. This is nested iteration, and the syllabus limits it to three levels. A fictional teacher prints part of the times tables:
FOR Table ← 1 TO 3
FOR Number ← 1 TO 4
OUTPUT Table * Number
NEXT Number
NEXT TableThink it through
Predict how many numbers the program outputs in total, and write out the first eight. Explain which loop changes faster.
- Hint 1: For each value of Table, how many times does the inner loop run?
Show a model answer
Twelve numbers in total: the inner loop runs 4 times for each of the 3 values of Table (3 × 4 = 12). The first eight are 1, 2, 3, 4, 2, 4, 6, 8. The inner loop changes faster: it completes all of its values for each single value of the outer loop.
Each time the outer loop moves on, the inner loop starts again from its first value. Trace the pass of the outer loop where Table is 3:
| Table | Number | OUTPUT |
|---|---|---|
| 3 | 1 | |
| 3 | ||
| 3 | ||
| 3 |
Show the completed table
| Table | Number | OUTPUT |
|---|---|---|
| 3 | 1 | 3 |
| 3 | 2 | 6 |
| 3 | 3 | 9 |
| 3 | 4 | 12 |
Check your understanding
Show the answer
Answer: B. 30, because the inner loop runs 6 times for each of the 5 passes.
For nested loops, multiply the number of passes of each loop.
Stage: Apply
Write loops of your own
Think it through
Write pseudocode that outputs the 12 times table in the form “1 x 12 = 12”, “2 x 12 = 24” and so on up to “12 x 12 = 144”. Say which kind of loop you chose and why.
Work this out on paper or the board first. Nothing here is marked: compare yours with the model answer.
- Hint 1: Is the number of repeats known before the loop starts?
- Hint 2: OUTPUT can show several values separated by commas, with spaces inside the quotation marks.
Show a model answer
FOR Number ← 1 TO 12
OUTPUT Number, " x 12 = ", Number * 12
NEXT NumberA count-controlled FOR loop, because the number of repeats (12) is known before the loop starts, and Number is the loop variable, so there is no need to change it inside the loop. The first line of output is “1 x 12 = 12”, the last is “12 x 12 = 144”.
Apply it
Show the answer
Answer: C. It outputs nothing, because 5 is already past 1; adding STEP -1 fixes it.
A FOR loop counts upwards by 1 unless STEP says otherwise.
Go deeper The same ideas in Python
for count in range(1, 6):
print(count * 2)
for number in range(10, -1, -5):
print(number)
coins = 7
drinks = 0
while coins >= 2:
coins = coins - 2
drinks = drinks + 1
print(drinks, "drinks,", coins, "coin left")
password = ""
while password != "Secret":
password = input("Enter the password ")
print("Welcome")range(1, 6)gives 1, 2, 3, 4, 5: it stops before the end value, so to matchFOR Count ← 1 TO 5the Python end is 6.range(10, -1, -5)gives 10, 5, 0: the third number is the step, and the end value -1 is again not reached.- A Python
forloop does not need a counter variable declared or aNEXT: the indentation shows the loop body. whileis the same idea as WHILE, with a colon and indentation instead of DO … ENDWHILE.- Python has no REPEAT … UNTIL. A common way to get the same effect is to set the variable so the first test passes (as above), or to write
while True:and usebreakonce the condition for stopping is met. Remember that the UNTIL condition says when to stop, and awhilecondition says when to continue.
Stage: Consolidate
Show what you know
Think it through
Explain the difference between FOR, WHILE and REPEAT … UNTIL to a friend, using a different example of your own for each, and say which of them can run zero times.
Show a model answer
A good answer matches each loop to its job. FOR repeats a number of times known in advance (print a class register of 30 names). WHILE tests first and carries on while the condition is true, so it can run zero times (keep taking 1 pound off a balance while it is at least 1). REPEAT … UNTIL runs the body first and stops when the condition becomes true, so it always runs at least once (keep asking for a locker code until it is right). Only WHILE can run zero times.
Apply it
Show the answer
Answer: C. INPUT before the loop, then WHILE Score <> 0 DO with the next INPUT at the end of the body.
When a special value ends the input and may come first, read once before a WHILE loop and again at the end of its body.
- Iteration repeats instructions; the repeated block is a loop.
- A count-controlled loop
FOR … NEXTrepeats a number of times known in advance; both end values are included, soFOR Count ← 4 TO 9runs 6 times.STEPchanges the jump (it may be negative). It runs zero times if the start is already past the end. - A pre-condition loop
WHILE … DO … ENDWHILEtests first, repeats while the condition is true and can run zero times. The body must change something in the condition, or the loop never ends. - A post-condition loop
REPEAT … UNTILtests after each pass, so it runs at least once, and its condition says when to stop. - Choose FOR when the count is known, WHILE when the body may not run at all, and REPEAT when it must run at least once.
- In nested loops, the inner loop runs completely for each pass of the outer loop, so the passes multiply. The syllabus’s limit is three levels.
- In Python,
range(1, 6)stops before 6.
Sources and scope
- What this lesson is. The fifth lesson of the Algorithms and Programming module, written for this site. It covers point 8.1.4(c) and the nested iteration of 8.1.5 of Cambridge IGCSE Computer Science 0478 (2026 to 2028, version 6). Its curriculum links are provisional and imply no review or endorsement by any examination board.
- Original material. Rocket Rescue, the drinks machine, the password program, the quiz game, the sign-up page, the teacher’s times-table program and Sam are fictional, written for this lesson. The pseudocode follows the layout in the syllabus’s pseudocode guide, and each program’s output was worked out by hand.
- Simplified on purpose. The password program compares text with
=and treats upper and lower case as different. The programs assume the user types sensible values; checking input (validation) is left to a later lesson. Nested loops stay within the syllabus’s three levels. Python’sbreakis mentioned in one line only. - Left to later lessons. Totalling, counting and finding the highest and lowest values with loops (Lesson 6).
A sequence of precise steps that solves a problem or completes a task.
An expression that is either true or false, such as Age >= 12, used to decide what a program does next.
A loop that repeats a fixed number of times, known before it starts. In pseudocode it is a FOR … NEXT loop.
Repeating instructions. A loop does this.
A set of instructions that is repeated, either a fixed number of times or until a condition says to stop.
A loop that tests its condition after each repeat, so its instructions always run at least once. In pseudocode it is a REPEAT … UNTIL loop.
A loop that tests its condition before each repeat, so its instructions may run zero times. In pseudocode it is a WHILE … ENDWHILE loop.
A precise but language-independent way of writing an algorithm, with set keywords such as IF, WHILE and OUTPUT, that is not tied to any one programming language.
A high-level programming language written as text, popular for learning and for real work, in which indentation shows which lines belong together.
A table used to follow an algorithm by hand, with a column for each variable and for the output and a row for each step, to record how the values change.
A named place in memory that stores a value which can change while a program runs.
Your progress on this lesson
Saved in this browser only. It is not sent anywhere, does not follow you to another device, and is lost if you clear this site’s data.
This browser is not allowing the site to save progress, so it will be forgotten when you leave the page.