Learn
8.1.4C.2 | PRE-CONDITION LOOPS: WHILE
01 | WHEN THE NUMBER OF REPETITIONS IS NOT KNOWN
A program keeps receiving amounts until a user enters a stop value. It might receive two amounts, twenty amounts or none. You cannot choose a fixed count before the user supplies those responses.
A WHILE loop uses a condition to decide whether to repeat. It checks before the body and continues only while the condition is TRUE.
This is pre-condition iteration: the test comes before each body execution. If the first test is FALSE, the body never runs.
You can also use WHILE for count-based examples, but its important feature is condition-controlled repetition. Follow the state that makes the condition true or false.
02 | READ THE WHILE FORMAT
Cambridge pseudocode uses a condition followed by DO, then a body closed by ENDWHILE.
DECLARE Count : INTEGER
Count ← 1
WHILE Count <= 3 DO
OUTPUT Count
Count ← Count + 1
ENDWHILE
OUTPUT "Finished"Count starts at one before the first test. Because one is at most three, the body runs: output one, then increase Count to two.
The loop checks the condition again before another body execution. It does not evaluate the condition once and then keep repeating without further tests.
| Part | Role |
|---|---|
| Count ← 1 | Initialise the value used by the first condition |
| Count <= 3 | Boolean continuation condition |
| OUTPUT Count; Count ← Count + 1 | Repeated work and progress update |
| ENDWHILE | Closes the body and leads back to the condition |
| OUTPUT "Finished" | Common following code after repetition ends |
03 | TRUE MEANS CONTINUE; FALSE MEANS LEAVE
Read WHILE Count <= 3 as “while Count is at most three, execute this body”. TRUE allows the next iteration. FALSE exits to the code after ENDWHILE.
| Condition check | Count at check | Count <= 3? | Action |
|---|---|---|---|
| 1 | 1 | TRUE | Output 1, then Count becomes 2 |
| 2 | 2 | TRUE | Output 2, then Count becomes 3 |
| 3 | 3 | TRUE | Output 3, then Count becomes 4 |
| 4 | 4 | FALSE | Skip the body and output Finished |
The number of checks differs from the number of iterations. Include the final false check when explaining why the loop stops.
The body outputs one, two and three, not four. Count becomes four through the final update, but the next false test prevents another body output.
04 | A FALSE FIRST CONDITION GIVES ZERO ITERATIONS
Change only the starting value to four.
Count ← 4
WHILE Count <= 3 DO
OUTPUT Count
Count ← Count + 1
ENDWHILE
OUTPUT "Finished"The first check asks whether four is at most three. It is false, so neither body instruction executes. Finished still appears afterwards.
Count remains four because the update was skipped. There is one condition check and zero body iterations.
This is why WHILE suits tasks where there may be nothing to process. Do not assume every loop executes at least once; that property belongs to the post-condition REPEAT structure introduced next.
05 | STEP THROUGH THE CHECKS
Choose a starting Count and predict each next event. Try one for several iterations and four for a zero-iteration run.
CURRENT COUNT
1BODY EXECUTIONS
0Ready to test Count <= 3.
The trace records conditions, body output and the counter update separately. The false test is followed by the common Finished output.
06 | THE CONTROL VALUE NEEDS A STARTING STATE
A condition reads values before entering the body. Those values must already have been assigned or supplied.
DECLARE Count : INTEGER
// Incorrect: Count has not been assigned
WHILE Count <= 3 DO
OUTPUT Count
Count ← Count + 1
ENDWHILEDeclaring Count gives its name and type, not a specified useful starting value. Initialise it before the WHILE test.
If the condition depends on user input, receive that first input before the loop. An INPUT inside the body cannot supply a value needed to decide whether the body is entered in the first place.
Ask two questions: where does the first controlling value come from, and what supplies or updates its later values?
07 | PROGRESS PREVENTS AN INFINITE LOOP
Remove the update from the count example while leaving Count initialised to one.
Count ← 1
WHILE Count <= 3 DO
OUTPUT Count
ENDWHILECount stays one, so the condition stays true. The loop keeps outputting one and never reaches Finished. This is an infinite loop under the stated instructions.
The correction is not just “add an update” anywhere. Count ← Count + 1 belongs inside the body so later checks see progress.
An update in the wrong direction can also fail. Decreasing Count from one while continuing as long as it is at most three never makes that condition false.
Not every WHILE needs a numeric increment: a new input, changed Boolean flag or another appropriate state change can provide progress.
08 | STOP ON A SENTINEL INPUT
A sentinel is a special value marking the end of data. Suppose valid amounts are non-negative whole numbers and minus one means stop. The stop value is not an amount to add.
DECLARE Amount : INTEGER
DECLARE Total : INTEGER
Total ← 0
OUTPUT "Enter an amount, or -1 to stop"
INPUT Amount
WHILE Amount <> -1 DO
Total ← Total + Amount
OUTPUT "Enter an amount, or -1 to stop"
INPUT Amount
ENDWHILE
OUTPUT "Total: ", TotalThe first input happens before WHILE so the initial condition can be tested. Each body execution adds the current amount, then receives the next value for the next check.
When minus one is received, the next condition is false and the body is skipped. The sentinel is excluded from the total.
Assume supplied values are non-negative whole numbers or the sentinel. The <> -1 test does not by itself validate that assumption or reject other negative values.
09 | TRACE DATA AND THE STOP VALUE
| Amount at check | Amount <> -1? | Total after any body work | Next input |
|---|---|---|---|
| 4 | TRUE | 4 | 0 |
| 0 | TRUE | 4 | 7 |
| 7 | TRUE | 11 | -1 |
| -1 | FALSE | 11 | No further input |
Zero is processed as a valid amount, even though adding it does not change the sum. The body still runs and requests another input.
There are three body iterations, four condition checks and four input executions including the initial input. The input prompt also occurs four times.
If the very first input is minus one, the loop runs zero times and outputs a total of zero. This is a valuable test for pre-condition behaviour.
10 | RANGE RETRY USES AN INVALIDITY CONDITION
A WHILE validation loop should continue while the current value is invalid. For a whole-number score from zero to ten, invalid means below zero OR above ten.
DECLARE Score : INTEGER
OUTPUT "Enter a whole-number score from 0 to 10"
INPUT Score
WHILE Score < 0 OR Score > 10 DO
OUTPUT "Out of range. Enter a score from 0 to 10"
INPUT Score
ENDWHILE
OUTPUT "Accepted score: ", ScoreAssume whole-number input. Twelve makes the condition true, so a replacement is requested. Eight makes it false, so the loop ends and eight is output as accepted.
A valid first input skips the retry body. The initial prompt and input still occurred, but the error message did not.
Using the valid-range condition Score >= 0 AND Score <= 10 with WHILE would repeat for valid values and stop for invalid ones. Choose a continuation condition that matches the body’s job.
11 | KEEP PROCESSING AND VALIDATION DISTINCT
The sentinel loop continues while there is an amount to process. The validation loop continues while a replacement is needed. Both use WHILE, but their conditions have different meanings.
Name the repeated job before choosing the condition. “Keep processing until stop” becomes continue while not stopped. “Keep retrying until valid” becomes continue while invalid.
A prompt is output, an INPUT supplies data and the condition checks it. No one keyword automatically performs all three jobs.
For numeric type handling, follow the stated input assumptions. A range loop assumes usable numbers; it does not magically convert arbitrary text into them.
12 | COMPARE WHILE WITH FOR
A WHILE can output one, two and three like a FOR, but it requires you to initialise and update its controlling value explicitly.
| Feature | FOR | WHILE |
|---|---|---|
| Repetition control | Counter progression through defined bounds | Boolean condition before the body |
| Initial counter | Provided by the FOR header | Explicit setup if using a counter |
| Progress | Provided by the counter increment | Relevant updates or inputs specified in the body |
| Typical task | Known count of scores or rounds | Process until a stop event, or retry while invalid |
Prefer a structure that clearly expresses the requirement. A fixed five-score task is naturally count-controlled; an unknown number of amounts ending at a sentinel is naturally condition-controlled.
Do not carry the FOR habit of an automatically advancing counter into WHILE. A condition alone does not change any value.
13 | CHOOSE TESTS THAT REVEAL THE STOPPING RULE
For Count <= 3, test starts one, three and four. One gives three iterations, three gives one, and four gives zero. These distinguish the included endpoint from the first excluded value.
For a sentinel task, test several amounts, zero as a valid amount and the sentinel as the first input. Check that the sentinel is excluded and that no extra input is requested after termination.
For range retry, test an initially valid value, an invalid value followed by a valid replacement, and accepted endpoints zero and ten.
Dry-run potential infinite loops for a few steps to show why the condition cannot change. Do not run an uncontrolled faulty loop in the browser or rely on waiting indefinitely to prove the problem.
14 | COMMON WHILE MISTAKES
First value unavailable: initialise or receive it before testing.
Missing progress: update the relevant state or receive the next value inside the body.
Wrong condition sense: WHILE continues when true, not when false.
Sentinel included: test the supplied value before processing it.
First input placed only inside: the pre-condition may read an unassigned value.
Final output inside: it repeats rather than reporting once after completion.
Always one iteration assumed: a false initial test skips the body entirely.
15 | EXPLAIN WHY THE LOOP STOPS
For the counter example: “After outputting three, the body increments Count to four. The next Count <= 3 check is false, therefore the loop exits before outputting four.”
For the sentinel: “The new input is received at the end of each body execution. When it is minus one, the next condition is false, so the stop value is not added.”
Explain the state change and the following test, rather than simply saying “the loop is finished”. That link shows understanding of pre-condition iteration.
The next lesson introduces REPEAT UNTIL, whose body executes before its stop condition is tested.