AQA GCSE Computer Science (8525), section 3.2.2 (Programming concepts)
What is iteration?
Iteration means repeating a set of statements. Each pass through the loop is one iteration.
Definite (count-controlled) iteration
The number of repeats is known in advance. A FOR loop is used.
FOR i ← 1 TO 5
OUTPUT i
ENDFOR
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
Indefinite (condition-controlled) iteration
The loop repeats until or while a condition is met, so the number of repeats is not known in advance. There are two kinds, depending on where the condition is tested.
Condition at the start
WHILE tests before each repeat. If the condition is false at the start, the loop runs zero times.
password ← ""
WHILE password ≠ "secret"
OUTPUT "Enter the password"
password ← USERINPUT
ENDWHILE
Condition at the end
The body runs at least once, then the condition is tested.
REPEAT
OUTPUT "Enter a number from 1 to 10"
number ← USERINPUT
UNTIL number >= 1 AND number <= 10
REPEAT ... UNTIL repeats until the condition becomes true. A DO ... WHILE loop is similar, but repeats while the condition is true.
DO
OUTPUT "Guess the number"
guess ← USERINPUT
WHILE guess ≠ target
Python
Python has for and while. A loop that must run at least once is written with while True and a break.
target = 7
while True: # at least once
guess = int(input("Guess: "))
if guess == target:
break
Which to use
| Loop | Use when |
|---|---|
| FOR | you know how many times to repeat |
| WHILE | you must check first, and it might not run at all |
| REPEAT ... UNTIL or DO ... WHILE | the body must run at least once, such as asking for input |
Common mistake: mixing up when the loop stops. WHILE repeats while the condition is true; REPEAT ... UNTIL repeats until the condition is true, so the condition is the opposite way round. Also, if nothing in a WHILE loop changes the condition, it will never stop.
Exam tip: state where the condition is tested (start or end) to show you understand the difference. Remember that a condition at the end means the loop runs at least once.
Check yourself
Which type of iteration is a FOR loop?
Definite (count-controlled) iteration.
What is the minimum number of times a REPEAT ... UNTIL loop runs?
Once, because the condition is tested at the end.
How many times does `FOR i ← 1 TO 4` repeat?
4 times.