Home / GCSE · AQA / Computer Science / Programming

CS6Iteration

3.2.2 Programming concepts

Iteration: definite and indefinite

Iteration is the repetition of a block of code. A loop saves writing the same lines again and again.

  • Use definite iteration when you know how many times before the loop starts: ‘for each of the 7 days’.
  • Use indefinite iteration when it depends on what happens: ‘keep asking until the answer is correct’.
  • An indefinite loop’s condition can be at the start (WHILE) or at the end (REPEAT … UNTIL, DO … WHILE). You need to understand both, even though Python only has the first.
  • A loop is shorter than repeated lines, and the number of passes is easy to change.
TypeAQA’s definitionLoops
Definite (count-controlled)The repetition of a block of code for a set number of timesFOR (and FOR … IN)
Indefinite (condition-controlled)The repetition of a block of code controlled by a condition. The number of iterations is not known when entering the block of codeWHILE, REPEAT … UNTIL, DO … WHILE
Iteration
The repetition of a block of code.
Definite iteration
The repetition of a block of code for a set number of times, e.g. a FOR loop.
Indefinite iteration
The repetition of a block of code controlled by a condition; the number of iterations is not known when entering the block of code, e.g. WHILE, REPEAT … UNTIL.
3.2.2 Programming concepts

FOR loops and range()

A FOR loop gives a counter variable each value in turn.

  • Pseudo-code: FOR … TO … ENDFOR. The upper (or lower) limit is included, and the counter never goes past it. STEP is 1 unless given, and can be negative.
  • The counter is declared in the FOR statement and doesn’t exist after the loop.
  • Python: range(stop) starts at 0; range(start, stop); range(start, stop, step). The stop value is never reached.
  • To match FOR i ← a TO b, use range(a, b + 1). Counting down, use range(a, b - 1, step).
AQA pseudo-codePythonValues
FOR i ← 1 TO 5for i in range(1, 6):1, 2, 3, 4, 5
FOR i ← 0 TO 6for i in range(7):0, 1, 2, 3, 4, 5, 6
FOR i ← 1 TO 5 STEP 2for i in range(1, 6, 2):1, 3, 5
FOR i ← 7 TO 3 STEP -2for i in range(7, 2, -2):7, 5, 3

Pseudo-code includes the limit; Python’s range stops before its stop value

Worked exampleWrite the Python for FOR i ← 3 TO 15 STEP 4 and list the values of i.
  1. 3, 7, 11, 15start at 3, add 4, stop at the limit 15 (it is included)
  2. range(3, 16, 4)the stop must be past 15, so 15 + 1 = 16
  3. Check: range(3, 16, 4) gives 3, 7, 11, 15 ✓19 would be past 16
for i in range(3, 16, 4):
    print(i)
Exam tipOnly just over half of students could pick out a definite loop in a Python MCQ. Count the values a range() gives on paper before you choose.
Loop counter
The variable in a FOR loop that takes each value in turn, e.g. i.
range(start, stop, step)
Python’s list of counter values: from start, adding step, stopping before stop.
3.2.2 Programming concepts

WHILE loops: condition at the start

A WHILE loop repeats while its condition is True. The condition is checked before each pass.

  • Output: 20, 13, 6. After 6, energy becomes −1, the condition is False, and the loop ends.
  • If the condition is False the first time, the body never runs. Starting with energy ← 0, nothing is output.
  • Something in the body must eventually make the condition False. If nothing does, the loop never ends (an infinite loop).
  • Use WHILE when the loop might not need to run at all.
AQA pseudo-codePython
energy ← 20
WHILE energy > 0
   OUTPUT energy
   energy ← energy - 7
ENDWHILE
energy = 20
while energy > 0:
    print(energy)
    energy = energy - 7
WHILE loop
Indefinite iteration with the condition at the start; it may run zero times.
Infinite loop
A loop whose condition never becomes False (or True, for UNTIL), so it never stops.
3.2.2 Programming concepts

REPEAT … UNTIL and DO … WHILE: condition at the end

With the condition at the end, the body runs first and is checked after, so it always runs at least once.

  • AQA pseudo-code: REPEAT … UNTIL condition stops when the condition becomes True.
  • Some languages use DO … WHILE condition: also checked at the end, but it carries on while the condition is True.
  • Python has neither. AQA accepts two ways to get the same effect: write the body once before a while loop (AQA’s Python guide), or use while True: with break at the bottom (AQA’s marking guidance).
WHILE … ENDWHILEREPEAT … UNTIL
Condition checkedAt the start of each passAt the end of each pass
Fewest passes01
The loop continues…while the condition is Trueuntil the condition is True (while it is False)

Where the condition is checked decides the smallest number of passes

Worked exampleThis REPEAT loop starts with energy at 0. What is output? Write it in Python.
energy ← 0
REPEAT
   OUTPUT energy
   energy ← energy - 7
UNTIL energy ≤ 0
  1. The body runs: OUTPUT 0, energy becomes −7no check before the first pass
  2. UNTIL −7 ≤ 0 is True, so the loop stopsthe check comes at the end
  3. A WHILE energy > 0 loop starting at 0 would output nothingthe check comes first
0 is output once.
energy = 0
while True:
    print(energy)
    energy = energy - 7
    if energy <= 0:
        break
Exam tipIn 2022 fewer than 1 in 10 students gave two clear differences between REPEAT … UNTIL and WHILE. Give where the condition is checked (end v start) and the fewest passes (at least once v possibly never). ‘One uses REPEAT and one uses WHILE’ earns nothing.
Exam tipNever write repeat or until in a Python answer: they don’t exist in Python. Use while.
REPEAT … UNTIL
Indefinite iteration with the condition at the end; runs at least once and stops when the condition is True.
DO … WHILE
Indefinite iteration with the condition at the end; runs at least once and continues while the condition is True.
3.2.2 Programming concepts

FOR … IN loops over strings and arrays

A FOR … IN loop runs once for each character in a string, or each item in an array (a Python list).

  • The loop variable (char) takes each character in turn, spaces included. Here it outputs 4 (H, W, U, K).
  • It is definite iteration: the number of passes is the number of characters.
  • Over an array: for score in scores: gives each item in turn. In AQA pseudo-code, you can’t change the array’s items through the loop variable.
  • Arrays are covered in Arrays and records; picking out characters by position is in String handling.
AQA pseudo-codePython
message ← 'Hello World UK'
capitals ← 0
FOR char IN message
   IF char ≥ 'A' AND char ≤ 'Z' THEN
      capitals ← capitals + 1
   ENDIF
ENDFOR
OUTPUT capitals
message = "Hello World UK"
capitals = 0
for char in message:
    if char >= "A" and char <= "Z":
        capitals = capitals + 1
print(capitals)
FOR … IN
A loop that runs once for each character of a string or each item of an array.
3.2.2 Programming concepts

Nested iteration

When an iteration statement appears inside another iteration statement, it is nested.

  • For each pass of the outer loop, the inner loop runs all the way through, starting again from its first value.
  • The inner body runs outer × inner times: 3 × 4 = 12 here.
  • The Python version prints each row on one line:
    1 2 3 4
    2 4 6 8
    3 6 9 12
  • The spec’s example nests a FOR inside a WHILE: different loop types can be nested. Selection can be nested inside iteration too.
AQA pseudo-codePython
FOR row ← 1 TO 3
   FOR col ← 1 TO 4
      OUTPUT row * col
   ENDFOR
ENDFOR
for row in range(1, 4):
    for col in range(1, 5):
        print(row * col, end=" ")
    print()
Exam tipNested loops cost the most marks in trace tables. Each time the outer counter changes, reset the inner counter to its first value, and run the inner loop to its last value before moving on.
Nested iteration
An iteration statement inside another iteration statement.
3.2.2 Programming concepts

Running totals, counters and ‘keep asking’ loops

Most loop questions use the same few patterns.

  • Set totals and counters to 0 before the loop. Inside the loop they would be reset on every pass.
  • Output a total after the loop, unless the question asks for output on every pass.
  • Only work out an average if the count is more than 0.
PatternBefore the loopInside the loopAfter the loop
Running totaltotal = 0total = total + valueprint(total)
Countercount = 0count = count + 1 (inside an if, to count only some values)print(count)
Keep asking until a valueinput the first valueuse it, then input the next value at the endthe loop stops when the stop value is entered
Worked examplePrices are entered until the user types 0. Output how many items there were and their total.
  1. total = 0 and items = 0start the total and the counter
  2. input the first price before the loopso the condition can be checked straight away
  3. while price != 0:indefinite: we don’t know how many prices
  4. add the price, add 1 to items, input the next pricethe last line of the body reads the next value
  5. Test: 2.5, 4, 0 → 2 items, total 6.50 stops the loop and isn’t counted
total = 0
items = 0
price = float(input("Price (0 to finish): "))
while price != 0:
    total = total + price
    items = items + 1
    price = float(input("Price (0 to finish): "))
print(f"{items} items, total {total}")
Exam tipIf a brief says ‘keep asking’, ‘repeat’ or ‘until’, you need a loop. Leaving out the iteration is the commonest big loss on code questions. Check that your loop is controlled by every condition in the brief.
3.2.2 Programming concepts

Loop bounds and off-by-one errors

A loop that runs one time too many or too few is called an off-by-one error. Count the passes before you write.

  • AQA’s FOR includes its limit, so FOR i ← 1 TO 5 is 5 passes. Python’s range excludes its stop value.
  • Indexes start at 0, so the last index of an array (or string) is its length − 1. That is why loops over indexes run to LEN(x) - 1.
  • To count the passes of FOR i ← a TO b STEP s: (b − a) DIV s + 1.
LoopValuesPasses
range(5)0, 1, 2, 3, 45
range(1, 5)1, 2, 3, 44
range(1, 6)1, 2, 3, 4, 55
count = 0, while count < 5, add 10 to 45
count = 0, while count <= 5, add 10 to 56
FOR i ← 0 TO LEN(names) - 1every index of namesLEN(names)
Worked exampleHow many times does FOR i ← 20 TO 5 STEP -5 run?
  1. i = 20, 15, 10, 5count down in 5s; the limit 5 is included
  2. (5 − 20) DIV (−5) + 1 = 3 + 1 = 4the formula agrees
4 times
Exam tipIn 2025 students wrote range(4) for five items and while counter <= 5 where < 5 was needed. Write down the first and last value your loop gives, then count them.
3.2.2 Programming concepts

Choosing the right loop

Read the brief, then pick the loop that matches it.

  • Any FOR loop can be rewritten as a WHILE loop: set the counter before the loop, test it in the condition, and add the step at the end of the body.
  • Changing a WHILE that counts into a FOR: find the first value, the last value and the step, then write the matching range.
The brief says…Best loop
Repeat exactly 12 times; for each of the 5 roundsFOR (definite)
For every character in a word; for every item in a listFOR … IN
Keep going until a total is reached or a valid value is enteredWHILE (indefinite)
Do it at least once, then repeat until the user chooses to stopCondition at the end: REPEAT … UNTIL (in Python, while True with break)
It may not need to run at allWHILE (condition at the start)
Worked exampleRewrite FOR i ← 1 TO 3 / OUTPUT i / ENDFOR as a WHILE loop.
  1. i ← 1the counter starts before the loop
  2. WHILE i ≤ 3the limit is included, so ≤
  3. OUTPUT i then i ← i + 1step 1, at the end of the body
i ← 1
WHILE i ≤ 3
   OUTPUT i
   i ← i + 1
ENDWHILE