CIE IGCSE | 8.1.4C.2 Pre-Condition Loops: WHILE

Lesson objective

Trace WHILE conditions before each body execution, initialise and update controlling values, and use sentinel inputs or range checks to control repetition.

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.

The condition is checked before each attempted iteration
PartRole
Count ← 1Initialise the value used by the first condition
Count <= 3Boolean continuation condition
OUTPUT Count; Count ← Count + 1Repeated work and progress update
ENDWHILECloses 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.

Three body executions require four condition checks
Condition checkCount at checkCount <= 3?Action
11TRUEOutput 1, then Count becomes 2
22TRUEOutput 2, then Count becomes 3
33TRUEOutput 3, then Count becomes 4
44FALSESkip 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

1

BODY EXECUTIONS

0

Ready 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
    ENDWHILE

    Declaring 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
    ENDWHILE

    Count 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: ", Total

    The 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

    First input four is supplied before the loop; final output is Total: 11
    Amount at checkAmount <> -1?Total after any body workNext input
    4TRUE40
    0TRUE47
    7TRUE11-1
    -1FALSE11No 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: ", Score

    Assume 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.

    Both can execute zero times in suitable circumstances
    FeatureFORWHILE
    Repetition controlCounter progression through defined boundsBoolean condition before the body
    Initial counterProvided by the FOR headerExplicit setup if using a counter
    ProgressProvided by the counter incrementRelevant updates or inputs specified in the body
    Typical taskKnown count of scores or roundsProcess 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.

    MATCH THE WHILE COMPONENT TO ITS ROLE

    Terminology

    Terminology

    WHILE loop

    A loop repeating its body while a condition is true.

    Pre-condition

    A test made before a body execution.

    Condition

    An expression evaluating to TRUE or FALSE.

    Continuation condition

    The condition that must be true for another iteration.

    DO

    Part of the Cambridge WHILE header introducing its body.

    ENDWHILE

    The keyword closing a WHILE loop.

    Loop body

    The instructions executed when the condition is true.

    Iteration

    One execution of the repeated body.

    Condition check

    An evaluation deciding whether the body should execute.

    Initialisation

    Supplying a starting value before the first test or calculation.

    Progress update

    A state change that affects a later condition check.

    Infinite loop

    Repetition that does not terminate under the stated instructions.

    Sentinel

    A special value marking the end of data rather than a value to process.

    Priming input

    An initial input received before the loop so the first condition can be tested.

    Zero iterations

    The body is skipped because the initial condition is false.

    Range retry

    Repetition receiving replacements while the current input is outside the permitted limits.

    Termination

    Leaving the loop when its continuation condition becomes false.

    Condition-controlled iteration

    Repetition governed by a Boolean condition rather than just predefined counter bounds.

    Questions

    Questions

    CHECK YOUR UNDERSTANDING

    Select all correct choices. Each exact set earns one point.

    1. Which statements describe WHILE?
    2. Count starts at four and the condition is Count <= 3. What happens?
    3. Count starts at one; body outputs Count then increments it; condition is <=3. Which are correct?
    4. Why can omitting the Count update cause an infinite loop?
    5. Which is required in the sentinel-input pattern?
    6. For amounts four, zero, seven and sentinel minus one, what is the total?
    7. Which WHILE condition retries whole-number scores outside zero to ten?
    8. Three body iterations in the basic count example require how many condition checks?

    EXPLAIN AND COMPARE

    Write your answers before revealing each sample.

    1. Define pre-condition iteration and explain why WHILE can execute zero times.

    2. Trace Count initially one with WHILE Count <= 3, OUTPUT Count, then Count ← Count + 1.

    3. Explain why the same loop without its update does not terminate.

    4. Describe the initial and later inputs in a sentinel-controlled WHILE.

    5. Calculate the total, body iterations and condition checks for inputs four, zero, seven, minus one.

    6. Explain why a valid first score skips a WHILE invalid-range retry.

    7. Compare FOR and WHILE for a fixed five-score task and an unknown sentinel-ended sequence.

    8. Suggest tests for WHILE Count <= 3 that check zero, one and several body iterations.

    BUILD IT | COUNT AND TOTAL UNTIL STOP

    Receive non-negative whole-number amounts until minus one is entered. Output the total and the number of amounts processed once after the loop. Exclude the sentinel; zero is a valid amount and counts as an entry. Assume every supplied value is non-negative or the sentinel. Write the complete algorithm and trace four, zero, seven, minus one.

    Reveal one possible solution
    DECLARE Amount : INTEGER
    DECLARE Total : INTEGER
    DECLARE EntryCount : INTEGER
    Total ← 0
    EntryCount ← 0
    OUTPUT "Enter an amount, or -1 to stop"
    INPUT Amount
    WHILE Amount <> -1 DO
        Total ← Total + Amount
        EntryCount ← EntryCount + 1
        OUTPUT "Enter an amount, or -1 to stop"
        INPUT Amount
    ENDWHILE
    OUTPUT "Total: ", Total
    OUTPUT "Amounts processed: ", EntryCount

    The total is eleven and entry count three. Zero adds nothing but still counts as a processed amount. Minus one is excluded from both summaries.

    Test: enter minus one first. The body runs zero times, and both summaries output zero. Explain why initialisation and priming input make this case work.

    Flashcards

    Flashcards

    Click to flip. Select the ideas you need to revisit.

    0 cards selected for revision.

      Selections are kept while this page is open.

      Workbook

      Workbook

      COMING SOON

      The workbook for 8.1.4C.2 Pre-Condition Loops: WHILE is coming soon. Complete the matching task and written questions in your exercise book.