[8.1.4c] Iteration

[8.1.4c] Iteration

Iteration means repeating a block of steps. Computers are good at doing the same action quickly and accurately many times, so loops are a core tool in every program. The IGCSE syllabus expects you to understand and use three main loop types: count-controlled loops (repeat a known number of times), pre-condition loops (test before each pass), and post-condition loops (test after each pass). Choosing the right kind of loop makes your algorithm simpler, safer, and easier to read.

Why programs need loops

Many real tasks involve repetition: summing exam marks in an array, asking a user again until a valid input is entered, or simulating days in a simple model. Without loops you would have to copy and paste the same code over and over, which is error-prone. With loops, you write the steps once and let the computer repeat them under control of a clear condition.

Three loop families at a glance

Each loop family has a distinct purpose. Use the tabbed examples to compare how they read and when they should be preferred.

Count-controlled: repeat N times when the count is known

Use a FOR loop when you know how many repetitions you need, e.g. printing the times table from 1 to 10 or processing a fixed number of records.

// CAIE Pseudocode
FOR i ← 1 TO 10
  OUTPUT i, " squared is ", i * i
NEXT i

# Python
for i in range(1, 11):
    print(i, "squared is", i * i)

Key idea: the loop variable automatically steps through a sequence of values. The bounds (start and end) must be correct to avoid missing or duplicating a pass.

Pre-condition: test before the body runs each time

A WHILE loop continues while a condition is TRUE. It is best when you do not know how many times you will repeat, but you know the rule for carrying on, e.g. continue reading until end-of-file.

// CAIE Pseudocode
DECLARE total : INTEGER ← 0
DECLARE input : INTEGER
INPUT input
WHILE input <> 0 DO
  total ← total + input
  INPUT input
ENDWHILE
OUTPUT "Sum = ", total

# Python
total = 0
value = int(input("Enter number (0 to stop): "))
while value != 0:
    total += value
    value = int(input("Enter number (0 to stop): "))
print("Sum =", total)

Key idea: you must set up the condition before the loop (initial read) and update it inside the loop (read again) to avoid an infinite loop.

Post-condition: always run at least once

REPEAT..UNTIL (post-condition) loops guarantee the body runs at least once, then continue until the condition becomes TRUE. They are ideal for menus that should display at least once regardless of previous input.

// CAIE Pseudocode
DECLARE choice : CHAR
REPEAT
  OUTPUT "(A)dd, (Q)uit"
  INPUT choice
  choice ← TOUPPER(choice)
  IF choice = 'A' THEN
    OUTPUT "Adding..."
  ENDIF
UNTIL choice = 'Q'

// Typical Python alternative using while True and break
while True:
    choice = input("(A)dd, (Q)uit: ").strip().upper()
    if choice == "A":
        print("Adding...")
    elif choice == "Q":
        break

Key idea: post-condition loops are best when at least one pass is required before you can sensibly test the condition.

Choosing the right loop

ScenarioBest loopReason
Display the 1 to 12 times tableFORKnown number of passes (12)
Keep asking until age between 0 and 120WHILE or REPEAT..UNTILUnknown repeats; validation loop
Show a menu at least once, exit on QREPEAT..UNTILMust run once before testing
Process each element of an arrayFORCount steps through indices

Off-by-one and boundary thinking

The most common loop bug is the off-by-one error: running one too many or one too few times. With count-controlled loops, check whether the end value is included. In CAIE pseudocode, FOR i ← 1 TO 5 runs five passes (1, 2, 3, 4, 5). In Python, range(1, 6) is needed to include 5. For pre- and post-condition loops, focus on when the condition becomes TRUE or FALSE, and ensure it is updated correctly inside the body.

// CAIE Pseudocode
FOR i ← 1 TO 5
  OUTPUT i
NEXT i

# Python
for i in range(1, 6):
    print(i)

Here both versions output 1 through 5 inclusive.

# Python off-by-one: prints 1..4 only
for i in range(1, 5):
    print(i)

Because Python's range stops before the end value, range(1, 5) excludes 5. Use 6 to include it.

# Python empty range: prints nothing
for i in range(5, 5):
    print(i)

If the start equals the end in Python's range, the loop body never runs. This can be desirable but often signals a boundary error.

Loop control and safety

  • Initialisation: set counters and totals to sensible starting values before the loop.
  • Update: ensure your loop variable or condition changes on each pass, otherwise you risk an infinite loop.
  • Termination: define clearly when the loop should stop, and test boundary cases to prove it does.
  • Nesting: loops can be placed inside other loops to process 2D structures (e.g. rows and columns), but complexity rises quickly, so keep each level clear.

Deep Dive: Choosing between WHILE and REPEAT..UNTIL for validation

For input validation, both structures work. A WHILE loop will only run the body if the value is already valid, which is unusual for validation. The common pattern is REPEAT..UNTIL: prompt the user, check the value, and repeat until it passes the test. In languages without a direct post-condition loop you can simulate it with while True plus break once the input is acceptable. The key is clarity: make the validation rule easy to read and place the prompt where the user expects it.

Key terminology

  • Iteration: repeating a block of statements controlled by a count or condition.
  • Count-controlled loop: a loop that runs a fixed number of times using a counter.
  • Pre-condition loop: tests before each pass (WHILE); may run zero times.
  • Post-condition loop: tests after each pass (REPEAT..UNTIL); runs at least once.
  • Off-by-one error: executing one too many or too few iterations due to incorrect bounds.

 Key Takeaways

  • Use FOR for a known number of passes, WHILE when continuing depends on a condition, and REPEAT..UNTIL when the body must run at least once.
  • Prevent off-by-one errors by checking whether the end value is included and by testing boundaries.
  • Always initialise variables, update the condition inside the loop, and define a clear stopping rule.
  • Choose structures that make intent obvious: validation suits post-condition; fixed lists suit count-controlled.
  • Test with edge cases to confirm the loop stops correctly and processes the full required range.