Learn
8.1.5.2 | NESTED ITERATION
01 | EVERY SEAT IN EVERY ROW
Imagine a small theatre with two rows of three seats. To label the seats, you begin with row one and visit seats one, two and three. Then you move to row two and visit seats one, two and three again.
The job has two layers of repetition: repeat for each row, and within that job repeat for each seat. Nested iteration means placing one loop inside another loop. Iteration is repetition; one execution of a loop’s repeated instructions is an iteration.
The loop’s body is the instruction or group of instructions repeated by that loop. The outer loop’s body contains the entire inner loop. Understanding this containment is the key to understanding the order of execution.
02 | RECALL WHAT ONE FOR LOOP DOES
A FOR loop uses a counter to repeat its body for a specified sequence of values. A loop counter is the variable holding the current value for that repetition.
Here Seat takes one, two and three in turn. The body is the OUTPUT instruction between FOR and NEXT. Both endpoints are included, so the output instruction executes three times.
NEXT Seat closes the loop controlled by Seat. It is not part of the repeated OUTPUT instruction and does not label a new seat by itself.
DECLARE Seat : INTEGER FOR Seat ← 1 TO 3 OUTPUT "Seat ", Seat NEXT Seat
03 | PLACE THAT LOOP INSIDE A ROW LOOP
Now put the seat loop inside a second FOR loop. Row is the outer counter; Seat is the inner counter. Different names let each loop keep track of its own job.
When Row is one, the entire inner loop executes with Seat equal to one, two and three. Only after it finishes does the outer loop move to Row two. Execution then reaches the inner FOR again, so its start value assigns Seat one again.
DECLARE Row : INTEGER
DECLARE Seat : INTEGER
FOR Row ← 1 TO 2
FOR Seat ← 1 TO 3
OUTPUT "Row ", Row, ", seat ", Seat
NEXT Seat
NEXT Row04 | VISUALISE THE ORDER THROUGH A GRID
Read the grid from left to right across row one, then left to right across row two. The numbered visits show the order in which the innermost OUTPUT executes.
VISIT 1
Row 1, seat 1VISIT 2
Row 1, seat 2VISIT 3
Row 1, seat 3VISIT 4
Row 2, seat 1VISIT 5
Row 2, seat 2VISIT 6
Row 2, seat 3Row stays unchanged while the seat loop runs. There is no visit with Row one and Row two happening together. The program performs these instructions in sequence.
A grid is useful for visualising the counters; this example does not require an array or store seat records. It simply outputs each pair.
05 | TRACE BOTH COUNTERS TOGETHER
Record the values at the instruction you are tracing. Each row below represents one execution of the innermost OUTPUT. It does not represent every loop-control step.
The change from visit three to visit four is the important transition. The first inner loop has finished; the outer counter advances; the inner loop starts again. Seat does not continue to four as the next output value.
| OUTPUT execution | Row | Seat | Output |
|---|---|---|---|
| 1 | 1 | 1 | Row 1, seat 1 |
| 2 | 1 | 2 | Row 1, seat 2 |
| 3 | 1 | 3 | Row 1, seat 3 |
| 4 | 2 | 1 | Row 2, seat 1 |
| 5 | 2 | 2 | Row 2, seat 2 |
| 6 | 2 | 3 | Row 2, seat 3 |
06 | COUNT EXECUTIONS AT THE CORRECT LEVEL
The outer body executes twice. It contains an inner loop whose body executes three times on each of those visits, so the innermost OUTPUT executes two times three, which is six.
Do not add two and three to get five. Multiplication applies here because each outer iteration performs a full set of three inner iterations.
Placement changes the answer. A message before the inner FOR but inside the outer loop appears twice. A message inside the inner loop appears six times. A message after the outer NEXT appears once.
FOR Row ← 1 TO 2
OUTPUT "Starting row"
FOR Seat ← 1 TO 3
OUTPUT "Checking seat"
NEXT Seat
OUTPUT "Row complete"
NEXT Row
OUTPUT "All rows complete"07 | TRY THE NESTED LOOP TRACE
Choose a small number of rows and seats per row, then step through the trace. The highlighted seat marks an execution of the inner body. Watch the inner counter restart when a new row begins.
The trace shows entry to each row, each output, row completion and final continuation. It deliberately avoids claiming a particular counter value after a FOR loop has finished.
08 | MATCH NEXT TO ITS OWN FOR
Close the inner FOR with NEXT Seat before closing the outer FOR with NEXT Row. The loops are contained one within the other, so the inner structure must finish first.
Indent the inner FOR and its NEXT by the same amount, then indent the inner body further. This makes it clear which instructions belong to which loop.
Using Row for both loop counters would interfere with the outer loop’s control. Choose distinct counters such as Row and Seat, Player and Attempt, or Day and Reading. Avoid changing a FOR counter manually inside its body.
09 | TWO SEPARATE LOOPS ARE NOT NESTED
If the loops are placed one after another, the first loop finishes completely before the second begins. The second does not repeat once for each first-loop iteration.
The code below outputs two row messages, then three seat messages: five messages in total. It does not produce six row-and-seat pairs. Nesting changes the relationship between the tasks, not merely the indentation.
FOR Row ← 1 TO 2 OUTPUT "Row ", Row NEXT Row FOR Seat ← 1 TO 3 OUTPUT "Seat ", Seat NEXT Seat
10 | RESET A LOCAL TOTAL, KEEP A GRAND TOTAL
Suppose two players each enter three valid INTEGER scores. We want a total for each player and one total for everyone.
PlayerTotal belongs to one player, so initialise it to zero inside the outer loop before that player’s inner loop starts. GrandTotal belongs to the whole activity, so initialise it once before the outer loop.
For scores two, four and six, player one totals twelve. Player two’s scores one, three and five total nine. GrandTotal ends at twenty-one. Resetting PlayerTotal prevents player two from inheriting player one’s twelve; resetting GrandTotal inside the outer loop would lose earlier players’ totals.
DECLARE Player : INTEGER
DECLARE Attempt : INTEGER
DECLARE Score : INTEGER
DECLARE PlayerTotal : INTEGER
DECLARE GrandTotal : INTEGER
GrandTotal ← 0
FOR Player ← 1 TO 2
PlayerTotal ← 0
FOR Attempt ← 1 TO 3
OUTPUT "Enter score for player ", Player, ", attempt ", Attempt
INPUT Score
PlayerTotal ← PlayerTotal + Score
NEXT Attempt
OUTPUT "Player total: ", PlayerTotal
GrandTotal ← GrandTotal + PlayerTotal
NEXT Player
OUTPUT "Grand total: ", GrandTotal11 | AN INNER LOOP CAN VALIDATE EACH INPUT
Nested loops do not have to use the same loop type. An outer FOR can request three accepted scores, while an inner REPEAT loop retries the input for the current score until it is valid.
Here a valid score is an INTEGER from zero to ten. Assume the input supplies integers; the range test does not convert arbitrary text. REPEAT runs its body at least once and stops when its UNTIL condition becomes TRUE.
Try the entries twelve, eight, minus one, six and ten. The first accepted score is eight, the second six and the third ten. There are three outer iterations but five inner input attempts in total. An invalid attempt does not advance ScoreNumber.
DECLARE ScoreNumber : INTEGER
DECLARE Score : INTEGER
FOR ScoreNumber ← 1 TO 3
REPEAT
OUTPUT "Enter score from 0 to 10"
INPUT Score
UNTIL (Score >= 0) AND (Score <= 10)
OUTPUT "Accepted score: ", Score
NEXT ScoreNumber12 | WHEN MULTIPLICATION IS NOT ENOUGH
The rule “outer count times inner count” works when the inner body executes the same known number of times for every outer iteration. A validation loop has a varying number of attempts, so you must trace the actual inputs.
A FOR loop can also have a limit that depends on the current outer counter. In this example, the inner body runs once for Row one, twice for Row two and three times for Row three. That gives one plus two plus three, or six outputs, rather than three times three.
FOR Row ← 1 TO 3
FOR Seat ← 1 TO Row
OUTPUT Row, ", ", Seat
NEXT Seat
NEXT Row13 | THREE LEVELS, THREE SEPARATE JOBS
Imagine two rooms, each containing two rows of three seats. One loop chooses the room, one chooses the row within that room, and one chooses the seat within that row.
The innermost output executes two times two times three: twelve times. For every new row, Seat starts at one. For every new room, execution reaches the Row FOR again, so Row starts at one too.
The Cambridge syllabus includes nested selection and iteration and does not require candidates to write more than three levels of nested statements. Clear counter names and indentation become especially important at this depth.
DECLARE Room : INTEGER
DECLARE Row : INTEGER
DECLARE Seat : INTEGER
FOR Room ← 1 TO 2
FOR Row ← 1 TO 2
FOR Seat ← 1 TO 3
OUTPUT Room, ", ", Row, ", ", Seat
NEXT Seat
NEXT Row
NEXT Room14 | SELECTION INSIDE A LOOP IS A DIFFERENT COMBINATION
A loop can contain an IF as well as another loop. If each seat must be checked for a fault, the inner loop visits every seat and an IF decides whether to output a warning for that seat.
In two rows of three seats, the check is reached six times, but the warning appears only for seats whose condition is TRUE. Do not assume every instruction text inside the inner loop must execute six times: a branch may skip some instructions.
Keep the ideas separate: iteration controls repetition, selection chooses a route. Combining them lets the program repeat a decision for many items.
15 | EXPLAIN THE ORDER AND THE PLACEMENT
A useful explanation is: “For each row, the inner loop visits all three seats before the outer counter advances, therefore the output executes six times across two rows.” This links the result to the execution order.
Before writing nested loops, identify what repeats at each level. Decide which values reset for each outer iteration and which must survive across the whole activity. Match every NEXT or UNTIL to its loop, then test a small example you can trace by hand.
Avoid assuming multiplication always gives the answer, forgetting that an inner FOR starts again, or placing a total’s reset at the wrong level. If a nested loop does not terminate, the outer loop cannot progress past it.
The next lesson introduces procedures, functions and parameters, which help organise reusable parts of a program.