Repetition — the REPEAT-UNTIL Loop
REPEAT-UNTIL runs the body first and tests afterwards. It is the third loop variant, and the syllabus asks you to solve the sum-of-n-numbers problem with all three.
The form
REPEAT
statements
UNTIL condition
The body executes, then the condition is tested. If false, repeat. If true, stop.
Two differences from WHILE, both important:
- The body always runs at least once. The test comes after.
- The condition is a stopping condition, not a continuing one. WHILE continues while true; REPEAT-UNTIL stops when true.
That second point reverses the logic, and reversing it incorrectly is the standard exam error.
WHILE and REPEAT-UNTIL compared
| WHILE | REPEAT-UNTIL | |
|---|---|---|
| Test position | Before the body | After the body |
| Minimum iterations | 0 | 1 |
| Condition means | Continue while true | Stop when true |
| Also called | Pre-test, entry-controlled | Post-test, exit-controlled |
The same loop written both ways:
i ← 1 i ← 1
WHILE i <= 5 DO REPEAT
PRINT i PRINT i
i ← i + 1 i ← i + 1
ENDWHILE UNTIL i > 5
Note the conditions are logical opposites: i <= 5 against i > 5. To
convert between the forms, negate the condition.
When the difference actually matters
For n = 0 in a sum-of-n-numbers program:
- WHILE:
count <= 0is false immediately. Zero iterations. Sum is 0. ✓ - REPEAT-UNTIL: the body runs once regardless, reading a number that shouldn't be read. Sum is wrong. ✗
So REPEAT-UNTIL is wrong for that problem unless you guard it:
IF n > 0 THEN
REPEAT
...
UNTIL count > n
ENDIF
This is the general rule: if zero iterations must be possible, use WHILE.
Where REPEAT-UNTIL is the natural choice
Menu-driven programs and input validation — anywhere the body must run at least once by the nature of the problem.
REPEAT
PRINT "Enter a mark between 0 and 100"
READ marks
UNTIL marks >= 0 AND marks <= 100
You must ask at least once, so a post-test loop expresses the intent exactly. A WHILE version needs a priming read and a duplicated prompt:
PRINT "Enter a mark between 0 and 100"
READ marks
WHILE marks < 0 OR marks > 100 DO
PRINT "Enter a mark between 0 and 100" duplicated
READ marks
ENDWHILE
Note the WHILE condition is the negation of the UNTIL condition, by De Morgan:
Getting this negation wrong — writing AND where OR belongs — is a frequent
and costly slip.
A note on Python
Python has no repeat-until. The idiom is:
while True:
marks = int(input("Enter a mark: "))
if 0 <= marks <= 100:
break
You still need the concept for pseudocode and for the exam; you just won't write it in Python directly.