CIE AS & A Level Computer Science, section 11.2 (Constructs)
Count-controlled loop (FOR)
Repeats a fixed number of times.
FOR Count ← 1 TO 10
OUTPUT Count * 2
NEXT Count
STEP changes the increment: FOR i ← 10 TO 0 STEP -2.
Pre-condition loop (WHILE)
The condition is tested before each repetition. If it is false at the start, the loop body runs zero times.
INPUT Number
WHILE Number <> 0
Total ← Total + Number
INPUT Number
ENDWHILE
Post-condition loop (REPEAT ... UNTIL)
The condition is tested after each repetition, so the body runs at least once. It repeats until the condition is true.
REPEAT
OUTPUT "Enter a number from 1 to 10"
INPUT Number
UNTIL Number >= 1 AND Number <= 10
Python
for count in range(1, 11): # FOR
pass
number = int(input())
while number != 0: # WHILE
number = int(input())
while True: # REPEAT ... UNTIL
number = int(input())
if 1 <= number <= 10:
break
Which loop to use
| Loop | Use when |
|---|---|
| FOR | you know in advance how many times to repeat |
| WHILE | the loop may need to run zero times, or the number of repetitions depends on a condition |
| REPEAT ... UNTIL | the body must run at least once, such as asking for input then validating it |
Common mistake: using a REPEAT ... UNTIL condition as though it were a WHILE condition. WHILE repeats while the condition is true; REPEAT repeats until it becomes true. Also, a FOR loop variable should not be changed inside the loop.
Exam tip: to justify a loop, state when the condition is tested and whether the body must run at least once. Example: "REPEAT...UNTIL, because the user must enter a value at least once before it can be checked".
Check yourself
Which loop always runs its body at least once?
REPEAT ... UNTIL (a post-condition loop).
Which loop is best when the number of repetitions is known?
A FOR (count-controlled) loop.
When is the condition tested in a WHILE loop?
Before each repetition.