CIE IGCSE | 8.1.5.2 Nested Iteration

Lesson objective

Construct and trace nested loops, explain how inner and outer iterations interact, and place counters, totals and validation correctly.

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 Row

04 | 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 1

VISIT 2

Row 1, seat 2

VISIT 3

Row 1, seat 3

VISIT 4

Row 2, seat 1

VISIT 5

Row 2, seat 2

VISIT 6

Row 2, seat 3

Row 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.

Counter values during the repeated OUTPUT, not after loop termination
OUTPUT executionRowSeatOutput
111Row 1, seat 1
212Row 1, seat 2
313Row 1, seat 3
421Row 2, seat 1
522Row 2, seat 2
623Row 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: ", GrandTotal

    11 | 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 ScoreNumber

    12 | 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 Row

    13 | 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 Room

    14 | 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.

    MATCH THE LOOP LINE TO ITS ROLE

    Terminology

    Terminology

    Iteration

    Repetition; one iteration is one execution of a loop body.

    Loop body

    The instruction or group of instructions repeated by a loop.

    Nested iteration

    A loop placed inside the body of another loop.

    Outer loop

    A loop containing another loop.

    Inner loop

    A loop contained inside another loop’s body.

    Loop counter

    A variable holding the current value of a controlled repetition.

    FOR

    A count-controlled loop over a specified sequence of counter values.

    NEXT

    Closes a FOR loop and identifies its counter.

    Inclusive limits

    Start and end values are included when reached by the counter sequence.

    Trace

    A record of instructions executed and values at specified steps.

    Indentation

    Leading spaces showing containment and structure.

    Initialisation

    Giving a value its starting state before it is needed.

    Running total

    A value updated by adding each relevant item.

    Grand total

    A total accumulated across the whole activity.

    Sequential loops

    Separate loops placed one after another rather than one inside another.

    Validation loop

    A loop repeating input until it meets specified checks.

    REPEAT UNTIL

    A post-condition loop whose body executes at least once and stops when the condition is TRUE.

    Variable inner count

    An inner loop’s number of iterations differs across outer iterations.

    Questions

    Questions

    CHECK YOUR UNDERSTANDING

    Select all correct choices. Each exact set earns one point.

    1. Which statements describe nested iteration?
    2. Two rows each have three seats. How many times does the inner OUTPUT execute?
    3. Which pairs occur consecutively in the two-by-three example?
    4. Which execution counts are correct?
    5. Which practices are appropriate?
    6. Where should totals be initialised?
    7. Inputs 12, 8, -1, 6, 10 supply three accepted scores from 0 to 10. Which are correct?
    8. FOR Row 1 TO 3 contains FOR Seat 1 TO Row. How many inner outputs occur?

    EXPLAIN AND COMPARE

    Write your answers before revealing each sample.

    1. Define nested iteration and distinguish outer and inner loops.

    2. Explain why two rows of three seats produce six innermost outputs.

    3. List the output pairs for the two-row, three-seat example.

    4. Compare two sequential loops of lengths two and three with nested loops of those lengths.

    5. Explain where PlayerTotal and GrandTotal must be reset.

    6. Trace the accepted scores and input attempt counts for 12, 8, -1, 6, 10.

    7. Calculate the innermost output count when Seat runs from 1 to Row for Row 1 to 3.

    8. Explain why an IF inside the inner loop may output fewer messages than the inner iteration count.

    BUILD IT | DAILY READINGS

    For each of two days, receive three valid INTEGER readings. Output each day’s total and a grand total after both days. Declare the counters and values, place the resets correctly, and trace day one readings two, four, six and day two readings one, three, five. The task assumes valid integer input.

    Reveal one possible solution
    DECLARE Day : INTEGER
    DECLARE ReadingNumber : INTEGER
    DECLARE Reading : INTEGER
    DECLARE DayTotal : INTEGER
    DECLARE GrandTotal : INTEGER
    GrandTotal ← 0
    FOR Day ← 1 TO 2
      DayTotal ← 0
      FOR ReadingNumber ← 1 TO 3
        OUTPUT "Enter reading for day ", Day, ", reading ", ReadingNumber
        INPUT Reading
        DayTotal ← DayTotal + Reading
      NEXT ReadingNumber
      OUTPUT "Day total: ", DayTotal
      GrandTotal ← GrandTotal + DayTotal
    NEXT Day
    OUTPUT "Grand total: ", GrandTotal

    Day one totals twelve, day two totals nine, and the grand total is twenty-one. There are six INPUT executions, two day-total outputs and one grand-total output. Extend the task by placing a suitable validation loop around each INPUT, without resetting DayTotal inside the retry loop.

    Flashcards

    Flashcards

    Click to flip. Select the ideas you need to revisit.

    0 cards selected for revision.

      Selections are kept while this page is open.

      Workbook

      Workbook

      COMING SOON

      The workbook for 8.1.5.2 Nested Iteration is coming soon. Complete the matching task and written questions in your exercise book.