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?

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 Count

Think 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?

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:

Following the FOR loop: one row for each pass
PassCountOUTPUT
11
2
3
4
5

    Show the completed table
    PassCountOUTPUT
    112
    224
    336
    448
    5510

    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

    How many times does the body of FOR Count ← 4 TO 9 run?
    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 Number

    If 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

    What does the FOR Number ← 10 TO 0 STEP -5 loop output?
    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.

    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.

    Following the drinks machine
    MomentCoinsDrinksCoins >= 2?OUTPUT
    Before the first pass70
    After pass 1
    After pass 2
    After pass 3
    After the loop13

      Show the completed table
      MomentCoinsDrinksCoins >= 2?OUTPUT
      Before the first pass70Yes
      After pass 151Yes
      After pass 232Yes
      After pass 313No
      After the loop133 drinks, 1 coin left

      Check your understanding

      The pupil starts with 1 coin instead of 7. How many times does the body of the WHILE loop run?
      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

      A programmer writes the loop below and the program never finishes. Why? WHILE Coins >= 2 DO Drinks ← Drinks + 1 ENDWHILE
      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.

      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:

      Following the password program
      PassPassword typedPassword = "Secret"?OUTPUT during the pass
      1abc
      2Secret
      After the loop

        Show the completed table
        PassPassword typedPassword = "Secret"?OUTPUT during the pass
        1abcNoEnter the password
        2SecretYesEnter the password
        After the loopWelcome

        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

        A programmer writes UNTIL Password <> “Secret” and finds the loop stops as soon as a wrong password is typed. Why?
        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.

        Which loop fits the task?
        TaskBest 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

          Show the completed table
          TaskBest loop
          Output every whole number from 1 to 100FOR
          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 starsFOR

          Apply it

          A fictional sign-up page keeps asking for an age until the user types a number from 1 to 120. Which loop is best, and what is its condition?
          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 Table

          Think it through

          Predict how many numbers the program outputs in total, and write out the first eight. Explain which loop changes faster.

          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:

          Nested loops: the pass where Table is 3
          TableNumberOUTPUT
          31
          3
          3
          3

            Show the completed table
            TableNumberOUTPUT
            313
            326
            339
            3412

            Check your understanding

            A program has FOR Row ← 1 TO 5 containing FOR Column ← 1 TO 6, and the inner body has one OUTPUT. How many times does that OUTPUT run?
            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.

            Show a model answer
            FOR Number ← 1 TO 12
              OUTPUT Number, " x 12 = ", Number * 12
            NEXT Number

            A 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

            Sam writes a countdown from 5 to 1 as: FOR Count ← 5 TO 1, then OUTPUT Count, then NEXT Count. What does it output, and how should it be fixed?
            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 match FOR Count ← 1 TO 5 the 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 for loop does not need a counter variable declared or a NEXT: the indentation shows the loop body.
            • while is 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 use break once the condition for stopping is met. Remember that the UNTIL condition says when to stop, and a while condition 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

            A fictional quiz game asks for scores one at a time and outputs “Recorded” for each one. The user types 0 to finish, and might type 0 straight away, in which case nothing should be recorded. Which description of the loop is correct?
            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 … NEXT repeats a number of times known in advance; both end values are included, so FOR Count ← 4 TO 9 runs 6 times. STEP changes the jump (it may be negative). It runs zero times if the start is already past the end.
            • A pre-condition loop WHILE … DO … ENDWHILE tests 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 … UNTIL tests 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’s break is mentioned in one line only.
            • Left to later lessons. Totalling, counting and finding the highest and lowest values with loops (Lesson 6).