11.2.4 Pre-condition and Post-condition Loops
A condition-controlled loop repeats according to a Boolean expression rather than a predetermined sequence of counter values. This makes it suitable when the number of repetitions is not known before execution begins.
The position and meaning of the condition depend on the loop structure.
A WHILE loop checks before executing its body, while a
REPEAT...UNTIL loop checks after the body has executed.
By the end of this section, you should be able to:
- Explain how a condition controls repetition.
- Write and trace a pre-condition
WHILEloop. - Explain why a
WHILEloop may execute zero times. - Write and trace a post-condition
REPEAT...UNTILloop. - Explain why a post-condition loop executes at least once.
- Distinguish a continuing condition from a stopping condition.
- Identify the statement that changes the loop condition.
- Recognise loops that cannot make progress towards termination.
- Use conditional repetition for validation and sentinel-controlled input.
- Create trace tables showing condition checks, updates and outputs.
Conditional Repetition
A conditional loop repeats while or until a Boolean condition reaches a particular result. The number of executions may vary each time the algorithm runs.
| Question | Count-controlled loop | Condition-controlled loop |
|---|---|---|
| What governs repetition? | A known sequence of control values | A Boolean condition |
| Is the number of repetitions known in advance? | Usually yes | Not necessarily |
| Typical use | Process exactly eight readings | Continue while unread data remains |
Every condition-controlled loop needs three logical parts:
- a value or state that affects the condition;
- a condition that is tested;
- an action that can eventually change the conditionβs result.
Pre-condition Loops
A pre-condition loop tests its condition before each possible execution of the body.
General pseudocode structure
WHILE <Condition> DO
<Statement or statements>
ENDWHILE
The body executes while the condition is TRUE. When the
condition is FALSE, execution continues after
ENDWHILE.
Original example: processing queued parcels
WHILE ParcelsWaiting > 0 DO
OUTPUT "Process the next parcel"
ParcelsWaiting β ParcelsWaiting - 1
ENDWHILE
OUTPUT "Queue complete"
| Condition result | Effect |
|---|---|
ParcelsWaiting > 0 is TRUE |
The body executes |
ParcelsWaiting > 0 is FALSE |
The body is skipped and the loop ends |
WHILE condition as the condition for
continuing the loop.
A WHILE Loop May Execute Zero Times
Because the condition is checked before the body, the first test can prevent any execution.
ParcelsWaiting β 0
WHILE ParcelsWaiting > 0 DO
OUTPUT "Process parcel"
ParcelsWaiting β ParcelsWaiting - 1
ENDWHILE
The first condition is:
0 > 0
This is FALSE, so the body executes zero times.
| Initial value | First condition result | Body executions |
|---|---|---|
ParcelsWaiting = 4 |
TRUE |
Four |
ParcelsWaiting = 1 |
TRUE |
One |
ParcelsWaiting = 0 |
FALSE |
Zero |
Post-condition Loops
A post-condition loop executes its body before testing the condition.
General pseudocode structure
REPEAT
<Statement or statements>
UNTIL <Condition>
The loop stops when the UNTIL condition becomes
TRUE. It repeats again while that condition remains
FALSE.
Original example: entering a storage percentage
REPEAT
OUTPUT "Enter storage usage from 0 to 100: "
INPUT StoragePercentage
UNTIL StoragePercentage >= 0
AND StoragePercentage <= 100
Input must occur before the program can decide whether the entered value is valid, so the body needs to run at least once.
UNTIL condition as the condition for
stopping the loop.
A Post-condition Loop Executes at Least Once
The body is reached before the first test. Even when the stopping condition is already satisfied by the initial state, the body still executes once.
Level β 50
REPEAT
OUTPUT Level
Level β Level + 10
UNTIL Level >= 50
| Stage | Level |
Effect |
|---|---|---|
| Before the loop | 50 | No condition has yet been checked |
| Body executes | 50 | 50 is output |
| Update | 60 | 10 is added |
| Condition check | 60 | 60 >= 50 is true, so the loop stops |
REPEAT...UNTIL loop.
Continuing Conditions and Stopping Conditions
The two loop structures often express opposite conditions.
| Loop | Condition means... | Body repeats when... | Loop stops when... |
|---|---|---|---|
WHILE |
Continue while this is true | The condition is TRUE |
The condition becomes FALSE |
REPEAT...UNTIL |
Stop when this is true | The condition is FALSE |
The condition becomes TRUE |
Equivalent logical ideas
Pre-condition form
WHILE AccessCode <> "OPEN" DO
INPUT AccessCode
ENDWHILE
Post-condition form
REPEAT
INPUT AccessCode
UNTIL AccessCode = "OPEN"
The first loop continues while the code is incorrect. The second loop stops when the code is correct.
WHILE to UNTIL without reversing its meaning may
produce the opposite behaviour.
Comparing Execution Order
| Feature | WHILE...DO...ENDWHILE |
REPEAT...UNTIL |
|---|---|---|
| Condition position | Before the body | After the body |
| Minimum executions | Zero | One |
| Condition interpretation | Continue condition | Stopping condition |
| First action | Evaluate the condition | Execute the body |
| Typical use | Process only while work exists | Obtain a value before testing it |
Same initial values, different result
Value β 20
Target β 20
WHILE version
WHILE Value < Target DO
OUTPUT Value
Value β Value + 5
ENDWHILE
The initial condition is false, so there is no output.
REPEAT version
REPEAT
OUTPUT Value
Value β Value + 5
UNTIL Value >= Target
The body executes first, so 20 is output once.
The Loop Must Make Progress
At least one statement inside the body should change a value that influences the condition.
Loop that makes progress
WHILE ItemsRemaining > 0 DO
OUTPUT ItemsRemaining
ItemsRemaining β ItemsRemaining - 1
ENDWHILE
The assignment moves ItemsRemaining towards zero, eventually
making the condition false.
Loop that does not make progress
WHILE ItemsRemaining > 0 DO
OUTPUT ItemsRemaining
ENDWHILE
If ItemsRemaining begins above zero, it never changes. The
condition therefore remains true.
Infinite Loops
An infinite loop continues without reaching its stopping state.
Missing update
Count β 1
WHILE Count <= 5 DO
OUTPUT Count
ENDWHILE
Count remains 1, so the condition stays true.
Update in the wrong direction
Temperature β 18
WHILE Temperature < 25 DO
Temperature β Temperature - 1
ENDWHILE
Subtracting 1 moves the value farther away from 25.
Impossible post-condition
Score β 20
REPEAT
Score β Score + 5
UNTIL Score < 0
The value increases, so the stopping condition cannot become true.
Using a Post-condition Loop for Input Validation
Validation often requires an input before the program can decide whether that input is acceptable.
Original example: fan-speed setting
REPEAT
OUTPUT "Enter a fan speed from 1 to 6: "
INPUT FanSpeed
IF FanSpeed < 1 OR FanSpeed > 6
THEN
OUTPUT "Invalid speed"
ENDIF
UNTIL FanSpeed >= 1 AND FanSpeed <= 6
The invalid condition used for the message and the valid condition used for stopping are logical opposites.
| Input | Valid? | UNTIL condition |
Next action |
|---|---|---|---|
| 0 | No | FALSE |
Repeat |
| 8 | No | FALSE |
Repeat |
| 4 | Yes | TRUE |
Stop |
AND.
Using a Sentinel Value
A special value can indicate that no more ordinary data will be entered.
Original example
CONSTANT END_READING = 999
REPEAT
OUTPUT "Enter a reading or 999 to finish: "
INPUT Reading
IF Reading <> END_READING
THEN
Total β Total + Reading
ReadingCount β ReadingCount + 1
ENDIF
UNTIL Reading = END_READING
The sentinel controls the loop but must not be processed as an ordinary reading.
A Reliable Method for Tracing Conditional Loops
| Stage | For WHILE | For REPEAT...UNTIL |
|---|---|---|
| 1 | Record current values | Record current values |
| 2 | Evaluate the condition | Execute the body |
| 3 | If true, execute the body | Record assignments and output |
| 4 | Record assignments and output | Evaluate the stopping condition |
| 5 | Return to the condition | If false, repeat the body |
Suggested trace-table columns
| Check number | Current values | Condition result | Body executed? | Update | Output |
|---|---|---|---|---|---|
| 1 | Record the starting state | TRUE or FALSE | Yes or no | Record changed values | Record any output |
Worked Example: Entering Air-Quality Readings
A monitoring system accepts any number of air-quality readings. The value 999 ends the input. The sentinel must not be included in the total or count.
Pseudocode
CONSTANT END_READING = 999
DECLARE Reading : REAL
DECLARE TotalReading : REAL
DECLARE ReadingCount : INTEGER
DECLARE AverageReading : REAL
TotalReading β 0
ReadingCount β 0
REPEAT
OUTPUT "Enter an air-quality reading or 999 to finish: "
INPUT Reading
IF Reading <> END_READING
THEN
TotalReading β TotalReading + Reading
ReadingCount β ReadingCount + 1
ENDIF
UNTIL Reading = END_READING
IF ReadingCount > 0
THEN
AverageReading β TotalReading / ReadingCount
OUTPUT "Average reading: ", AverageReading
ELSE
OUTPUT "No readings were entered"
ENDIF
Trace with inputs 42, 57, 51 and 999
| Iteration | Input | Ordinary reading? | Total | Count | Stop condition |
|---|---|---|---|---|---|
| 1 | 42 | Yes | 42 | 1 | 42 = 999 is false |
| 2 | 57 | Yes | 99 | 2 | 57 = 999 is false |
| 3 | 51 | Yes | 150 | 3 | 51 = 999 is false |
| 4 | 999 | No | 150 | 3 | 999 = 999 is true |
Final calculation
AverageReading β 150 / 3
AverageReading β 50
UNTIL condition true.
Interactive: Conditional Loop Tracer
Use identical starting values with both loop structures. The animation shows whether the condition is checked before or after the body and highlights the final test that stops repetition.
Common Mistakes and Misconceptions
-
Assuming both loops test first:
REPEAT...UNTILexecutes the body before its first test. - Assuming both loops may execute zero times: only a pre-condition loop can skip its body completely.
-
Confusing the condition meanings:
WHILEstates when to continue;UNTILstates when to stop. -
Using the same condition during conversion: an
equivalent
UNTILcondition is usually the logical opposite of aWHILEcondition. - Missing the update: no condition variable changes during the body.
- Updating in the wrong direction: the value moves farther from the stopping state.
- Testing input before it exists: a WHILE loop may require an initial input before the loop or another initial value.
- Counting the final failed WHILE test as an iteration: the condition is checked, but the body does not execute.
- Processing a sentinel: the end marker is added to a total or count.
- Using OR inside an inclusive validity condition: values must satisfy both the lower and upper limits.
Practice
Question 1: trace a WHILE loop
Value β 4
WHILE Value < 13 DO
OUTPUT Value
Value β Value + 3
ENDWHILE
State the output, final value of Value and number of body
executions.
Question 2: zero executions
BatteryLevel β 90
WHILE BatteryLevel < 80 DO
OUTPUT "Charge"
BatteryLevel β BatteryLevel + 5
ENDWHILE
Explain why the body does not execute.
Question 3: trace REPEAT...UNTIL
Level β 6
REPEAT
OUTPUT Level
Level β Level + 4
UNTIL Level >= 17
State the output, final value and number of body executions.
Question 4: identify the infinite loop
Remaining β 7
WHILE Remaining > 0 DO
OUTPUT Remaining
Remaining β Remaining + 1
ENDWHILE
Explain why the loop does not terminate and correct the update.
Question 5: input validation
Write pseudocode that repeatedly inputs
Brightness until the entered integer is from 10 to 90
inclusive.
Question 6: convert the condition
Rewrite this as a post-condition loop:
INPUT Command
WHILE Command <> "STOP" DO
OUTPUT "Command accepted"
INPUT Command
ENDWHILE
Question 7: sentinel-controlled total
Write pseudocode that inputs package masses until the value
-99 is entered. The sentinel must not be included in the
total.
Question 8: compare minimum executions
Explain what happens when Value = Limit before each loop:
WHILE Value < Limit DO
OUTPUT Value
ENDWHILE
REPEAT
OUTPUT Value
UNTIL Value >= Limit
Question 9: correct the validity condition
REPEAT
INPUT Percentage
UNTIL Percentage >= 0 OR Percentage <= 100
Explain why the condition is incorrect and rewrite it.
Show suggested answers
Question 1
- Output:
4, 7, 10 - Final value:
13 - Body executions: three
Question 2
The first condition is 90 < 80, which is false. A
pre-condition loop checks before entering the body.
Question 3
- Output:
6, 10, 14 - Final value:
18 - Body executions: three
Question 4
Adding 1 moves Remaining farther above zero. A suitable
correction is:
Remaining β Remaining - 1
Question 5
REPEAT
OUTPUT "Enter brightness from 10 to 90: "
INPUT Brightness
UNTIL Brightness >= 10 AND Brightness <= 90
Question 6
REPEAT
INPUT Command
IF Command <> "STOP"
THEN
OUTPUT "Command accepted"
ENDIF
UNTIL Command = "STOP"
Question 7
CONSTANT END_MASS = -99
TotalMass β 0
REPEAT
INPUT PackageMass
IF PackageMass <> END_MASS
THEN
TotalMass β TotalMass + PackageMass
ENDIF
UNTIL PackageMass = END_MASS
OUTPUT "Total mass: ", TotalMass
Question 8
The WHILE condition is initially false, so its body executes
zero times. The REPEAT...UNTIL body executes once before the
condition is tested.
Question 9
Almost every value is either at least zero or at most 100, so the
OR expression accepts invalid inputs. Both boundaries must
be satisfied:
UNTIL Percentage >= 0 AND Percentage <= 100
Review
| Feature | WHILE loop | REPEAT...UNTIL loop |
|---|---|---|
| Test position | Before the body | After the body |
| Minimum body executions | Zero | One |
| Condition meaning | Continue while true | Stop when true |
| Typical structure | WHILE...DO...ENDWHILE |
REPEAT...UNTIL |
| Progress requirement | A value used by the condition must change so that termination can eventually occur | |