A-Level Computer Science / Unit 11: Structured Programming

11.2.4 Pre-condition and Post-condition Loops

πŸ”’ Lesson slides are available to signed-in users. Sign in

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 WHILE loop.
  • Explain why a WHILE loop may execute zero times.
  • Write and trace a post-condition REPEAT...UNTIL loop.
  • 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.
Connection to nearby pages: 11.2.3 covered loops with a known control sequence. This page covers repetition whose length depends on changing program data. Full loop-choice justification is developed in 11.2.5.

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.

Condition-controlled loop: a loop whose repetition depends on the result of a Boolean expression.
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:

  1. a value or state that affects the condition;
  2. a condition that is tested;
  3. an action that can eventually change the condition’s result.
Common misconception: writing a condition does not guarantee that the loop will stop. The values used by the condition must change in a suitable way.

Pre-condition Loops

A pre-condition loop tests its condition before each possible execution of the body.

Pre-condition loop: a loop that checks its condition before the repeated statements.

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
Read a 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
Common mistake: do not automatically create a trace-table row for the loop body. Evaluate the initial condition first.

Post-condition Loops

A post-condition loop executes its body before testing the condition.

Post-condition loop: a loop that tests its condition after the repeated statements.

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.

Read an 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
Common misconception: the program does not check whether the condition is already true before entering a 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.

Common mistake: copying the same condition from 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.

Loop update: a statement that changes data used by the loop condition so that termination can eventually be reached.
When checking a conditional loop, underline every identifier in its condition. Then find where each relevant identifier can change.

Infinite Loops

An infinite loop continues without reaching its stopping state.

Infinite loop: a loop that does not terminate because its control condition never reaches the required result.

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.

Important: a variable changing is not enough. It must change in a direction that can eventually produce the required condition result.

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
For a valid inclusive range, the stopping condition usually joins the lower and upper comparisons using AND.

Using a Sentinel Value

A special value can indicate that no more ordinary data will be entered.

Sentinel value: a special input used to signal the end of a data sequence.

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.

Common mistake: adding the sentinel to a total or counting it as a normal data item.

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
Include the final condition check that stops a loop, but do not record an additional body execution after that check.

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
Show both roles of the sentinel: it prevents the value from being processed and it makes the 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.

Pre-condition WHILE loop

The condition is checked before every possible execution.

The loop can progress towards the target.

WHILE Level < Target DO
    OUTPUT Level
    Level ← Level + Increase
ENDWHILE

Trace

Output so far: --
Current level: 10
Condition: Not checked
Body executions: 0

Step 1

Prepare the loop

The starting values are available before the first condition check.

Set the starting level equal to the target. The WHILE body will be skipped, while the REPEAT body will still execute once.

Common Mistakes and Misconceptions

  • Assuming both loops test first: REPEAT...UNTIL executes 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: WHILE states when to continue; UNTIL states when to stop.
  • Using the same condition during conversion: an equivalent UNTIL condition is usually the logical opposite of a WHILE condition.
  • 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
Final exam tip: state where the condition is checked, what Boolean result causes repetition, the minimum number of executions and which statement moves the loop towards termination.