CIE IGCSE | 8.1.4C.4 Choosing and Comparing Loop Types

Lesson objective

Choose and justify suitable loop types, compare their first tests and stopping rules, and adapt input and processing when translating between structures.

Learn

8.1.4C.4 | CHOOSING AND COMPARING LOOP TYPES

01 | DO NOT CHOOSE FROM THE KEYWORD ALONE

You now know three loop structures, but a scenario does not always name the one you should use. It describes a job: receive five scores, process values until a stop marker, or ask for a valid menu choice.

The useful question is not “which loop do I remember best?” It is “what controls this repetition?” A fixed progression, a condition before processing, and a required first action describe different needs.

Several correctly designed algorithms can sometimes solve the same task. Choose a structure that expresses the requirement clearly, then justify it through the task’s count, stopping rule and first-iteration behaviour.

This lesson connects the earlier examples and shows why converting a loop requires more than replacing its opening keyword.

02 | THREE STRUCTURES SIDE BY SIDE

Cambridge pseudocode conventions
FeatureFORWHILEREPEAT UNTIL
Main controlCounter progression and boundsBoolean continuation conditionBoolean stopping condition
First bodyOnly if progression has an applicable valueOnly if the first condition is trueBefore the first stopping check
True conditionNot expressed as a WHILE-style Boolean headerContinue into the bodyStop after the body
Minimum body executionsCan be zeroCan be zeroAt least one when reached
ProgressCounter increment provided by FORUpdates/inputs specified by the algorithmUpdates/inputs specified by the algorithm
Typical useDefined count of itemsPossibly empty condition-controlled processingReceive an attempt, then check completion

FOR is count-controlled; WHILE and REPEAT UNTIL are condition-controlled. A previously supplied count can still control a FOR: it need not be a literal known when writing the program.

The table is a guide to behaviour, not a claim that each loop can solve only one category of problem.

03 | ASK THREE QUESTIONS ABOUT THE TASK

What repeats? Identify the actual body: one input, one record calculation or one attempt. Avoid treating the whole paragraph as a single vague instruction.

Must a first body execution happen? A required input attempt is different from processing a list that may contain no items.

What ends repetition? A specified item count suggests FOR; a state checked before work suggests WHILE; completion checked after required work suggests REPEAT UNTIL.

Then ask what gives the first controlling value and what changes it later. These questions reveal missing initialisation, missing input and infinite-loop risks before you write a full algorithm.

04 | WHEN A DEFINED COUNT MAKES FOR CLEAR

A teacher needs exactly five valid scores and their total. FOR makes the five accepted entries explicit.

Total ← 0
FOR StudentIndex ← 1 TO 5
    INPUT Score
    Total ← Total + Score
NEXT StudentIndex
OUTPUT Total

Assume suitable INTEGER declarations and valid input. There are five input executions. Total starts once before repetition and the final output appears once after it.

A WHILE can also implement this count, but needs an initial counter, a bound condition and a body update. Those extra responsibilities create more opportunities to omit progress or misplace the starting value.

A clear justification is: “The task specifies five scores, so a count-controlled FOR directly represents the required number of repetitions.”

05 | WHEN A BEFORE-BODY TEST MAKES WHILE CLEAR

A user enters non-negative amounts, ending with minus one. There may be no amounts at all if the first response is the sentinel.

Total ← 0
INPUT Amount
WHILE Amount <> -1 DO
    Total ← Total + Amount
    INPUT Amount
ENDWHILE
OUTPUT Total

Assume appropriate INTEGER declarations and inputs that are non-negative or the sentinel. The first input establishes the initial condition. A stop value is tested before processing, so it is never added.

The body count is unknown in advance and can be zero. WHILE expresses “process while this is an ordinary amount”. Each body receives the next input before the following test.

Prompts can be added before each INPUT. They improve the interaction but do not change the sentinel logic or validate other possible input types.

06 | WHEN A REQUIRED FIRST ATTEMPT MAKES REPEAT CLEAR

A program must ask for a whole-number score, then check whether it lies from zero to ten inclusive. REPEAT naturally places input before its first acceptance test.

REPEAT
    OUTPUT "Enter a whole-number score from 0 to 10"
    INPUT Score
UNTIL Score >= 0 AND Score <= 10
OUTPUT "Accepted score: ", Score

Assume Score is declared INTEGER and every supplied input is a whole number. A valid first input gives one iteration. Invalid inputs cause more attempts, until the valid-range condition becomes true.

A good justification is: “At least one response must be received before validity can be checked, so the post-condition loop fits the required first attempt.”

This is not a guarantee that the user will ever supply a valid response. The algorithm’s termination still depends on its state and input sequence.

07 | THREE COUNTER LOOPS CAN AGREE FOR A NORMAL CASE

These fragments assume Counter is declared INTEGER. Each outputs one, two and three for the shown bounds.

// FOR
FOR Counter ← 1 TO 3
    OUTPUT Counter
NEXT Counter
// WHILE
Counter ← 1
WHILE Counter <= 3 DO
    OUTPUT Counter
    Counter ← Counter + 1
ENDWHILE
// REPEAT UNTIL
Counter ← 1
REPEAT
    OUTPUT Counter
    Counter ← Counter + 1
UNTIL Counter > 3

FOR supplies its own counter progression. The condition-controlled loops need explicit assignment and update. WHILE uses a true-to-continue test; UNTIL uses a true-to-stop test.

Three matching output lists establish agreement for this starting case, not universal equivalence for every bound or initial state.

08 | THE EMPTY CASE REVEALS THE DIFFERENCE

Now use a target count N and start Counter at one. FOR uses 1 TO N; WHILE tests Counter <= N; the naive REPEAT version stops when Counter > N after output and increment.

The REPEAT body outputs before checking whether any output was required
Target NFOR outputsWHILE outputsNaive REPEAT outputs
31, 2, 31, 2, 31, 2, 3
1111
0NoneNone1

For N zero, the FOR has no applicable default upward counter value and WHILE is false initially. REPEAT still outputs one, then stops. That violates a task requiring exactly zero outputs.

Choose FOR or WHILE for a count that may be zero, or explicitly guard the REPEAT with IF N > 0. Do not assume every translation preserves empty-case behaviour.

09 | COMPARE THE THREE TRACES INTERACTIVELY

Choose a target count from zero to five. Predict the output list for each structure, especially when the target is zero.

FOR | 1 TO N

Not run

WHILE | COUNTER <= N

Not run

REPEAT | UNTIL COUNTER > N

Not run

The REPEAT column deliberately uses the unguarded translation above. Its zero-target result demonstrates why the first-body behaviour matters, rather than recommending that version for an empty task.

10 | TRANSLATE A RANGE RETRY CAREFULLY

Both following algorithms request input until a valid whole-number score from zero to ten is available. Assume an INTEGER Score declaration and whole-number inputs.

// WHILE version: receive the first value before testing
INPUT Score
WHILE Score < 0 OR Score > 10 DO
    INPUT Score
ENDWHILE
// REPEAT version: receive the first value inside the body
REPEAT
    INPUT Score
UNTIL Score >= 0 AND Score <= 10

WHILE continues on invalidity; UNTIL stops on validity. The lower and upper comparisons change along with OR versus AND because the two conditions describe complementary states.

Inputs twelve, minus one and eight are received three times in either version. WHILE has two retry-body iterations because its first input is outside; REPEAT has three input-body iterations.

Equivalent accepted results do not imply identical body counts. Compare the jobs performed, not just the position of a keyword.

11 | TRANSLATE SENTINEL PROCESSING WITHOUT INCLUDING THE SENTINEL

The WHILE amount example tested before adding. A REPEAT version receives every response inside its body, so guard its addition.

Total ← 0
REPEAT
    INPUT Amount
    IF Amount <> -1
      THEN
        Total ← Total + Amount
    ENDIF
UNTIL Amount = -1
OUTPUT Total

With four, zero, seven and minus one, both correctly designed versions output eleven. The WHILE body runs three times; the REPEAT body runs four times because its sentinel input is received inside the body.

If minus one comes first, WHILE processes zero items with zero body iterations. REPEAT also processes zero items, but receives the sentinel in one guarded body iteration.

Removing the guard would add minus one before UNTIL can stop, changing the total. A translation must preserve processing rules, not just the stopping value.

12 | COMBINE LOOP TYPES FOR DIFFERENT JOBS

A school needs attendance for four classes. Each class must supply a whole number from zero to thirty, with invalid attempts retried.

The outer task has four accepted class values, so FOR is a clear choice. The inner task has an unknown number of attempts but needs at least one response, so REPEAT UNTIL fits that input retry.

Total ← 0
FOR ClassIndex ← 1 TO 4
    REPEAT
        INPUT Attendance
    UNTIL Attendance >= 0 AND Attendance <= 30
    Total ← Total + Attendance
NEXT ClassIndex
OUTPUT Total

Assume suitable INTEGER declarations and whole-number inputs. An invalid attempt does not advance the outer class counter: the inner retry remains within the same class until acceptance.

Do not force a whole scenario into one loop type. Decomposition can reveal several repeated jobs, each with its own control.

13 | CHOOSE TESTS THAT CHALLENGE YOUR CHOICE

For a defined count, test zero, one and several items where those counts are permitted. For STEP, test a final bound that is reached and one skipped by the progression.

For validation, test a valid first response, invalid-then-valid input and accepted endpoints. For a sentinel, test the stop value first and a sequence containing a valid zero.

For a translation, compare accepted data, summaries, prompts required by the task and termination. A changed body count is not automatically wrong if the structure has moved the input, but a changed total or missing required first response may be.

Also check progress: FOR controls its counter, while WHILE and REPEAT need appropriate updates or inputs. Do not run an uncontrolled faulty loop merely to see whether it eventually stops.

14 | EXPLAIN A SUITABLE CHOICE WITHOUT OVERCLAIMING

“FOR is suitable because the task specifies four accepted class values” is stronger than “FOR is the easiest”. It links structure to requirement.

“WHILE tests the sentinel before processing, therefore a first stop value produces no processing iterations” explains both position and effect.

“REPEAT obtains an input before checking it, so the required first attempt happens” explains a post-condition benefit.

Acknowledge alternatives when appropriate. A correctly designed WHILE can receive five items; a guarded REPEAT can handle sentinel data. The goal is clear, correct control, not a claim that only one keyword is ever possible.

15 | FINAL LOOP-CHOICE CHECK

Count: is a defined counter progression enough, and can the required number be zero?

First action: must the body execute before any condition can be tested?

Condition sense: does true mean continue or stop in this structure?

State: where does the first controlling value come from, and what changes it?

Processing: are invalid attempts and stop markers excluded correctly?

Placement: which statements repeat and which must happen once?

Use these questions before writing a complete solution and again when testing it. The next lesson applies repetition to totalling and counting in programs.

CHOOSE A CLEAR LOOP ARRANGEMENT

Terminology

Terminology

Iteration

Repetition of instructions.

Count-controlled iteration

Repetition governed by a defined counter progression.

Condition-controlled iteration

Repetition governed by a Boolean condition.

Pre-condition loop

A loop testing its condition before the body, such as WHILE.

Post-condition loop

A loop testing after the body, such as REPEAT UNTIL.

Continuation condition

A condition whose true result allows another body execution.

Stopping condition

A condition whose true result ends post-condition repetition.

Loop body

The statements repeated by the structure.

Priming input

An input received before a pre-condition loop’s first test.

Sentinel

A special value marking the end of ordinary data.

Processing guard

A decision excluding a received value from inappropriate processing.

Zero-iteration case

A case in which the loop body never runs.

Minimum-one behaviour

The first body runs before a post-condition test.

Loop translation

Rewriting repetition using another structure while preserving required behaviour.

Equivalent behaviour

The same required results and effects for the relevant inputs, even if internal steps differ.

Nested loops

One repeated structure inside another.

Progress

A relevant state change that can lead towards termination.

Boundary case

Input or initial state near a decision or repetition limit.

Questions

Questions

CHECK YOUR UNDERSTANDING

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

1. Which choices express a defined count directly?
2. Which structures can skip their body entirely in suitable cases?
3. Which statements about condition sense are correct?
4. For a required input followed by a validity test, which is a clear choice?
5. A naive counter REPEAT starts at one and stops after update when Counter > N. For N zero, what happens?
6. Which amendments are needed when translating a WHILE invalid-range retry to REPEAT?
7. What protects a REPEAT sentinel total?
8. Four accepted classes each need range retries. Which arrangement is clear?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Compare FOR, WHILE and REPEAT UNTIL on control and first-body behaviour.

2. Explain why FOR is a clear choice for five valid scores.

3. Explain why a pre-condition sentinel loop can process zero items.

4. Explain why REPEAT fits a required first input attempt.

5. Compare the naive counter versions for N zero.

6. Describe the input-placement and condition changes for a WHILE-to-REPEAT range retry.

7. Calculate total and body counts for inputs four, zero, seven, minus one in the two correct sentinel patterns.

8. Explain how an outer FOR and inner REPEAT handle four accepted classes with invalid retries.

BUILD IT | FOUR CLASSES, VALID INPUT

Receive attendance for four classes. Each whole-number entry must be from zero to thirty inclusive; request a replacement until valid. Output the total once after all classes. Choose and justify both loop structures, write the complete algorithm and trace attempts twelve, thirty-one, eighteen, zero and thirty. Assume whole-number inputs.

Reveal one possible solution
DECLARE ClassIndex : INTEGER
DECLARE Attendance : INTEGER
DECLARE Total : INTEGER
Total ← 0
FOR ClassIndex ← 1 TO 4
    REPEAT
        OUTPUT "Enter attendance for class ", ClassIndex
        INPUT Attendance
    UNTIL Attendance >= 0 AND Attendance <= 30
    Total ← Total + Attendance
NEXT ClassIndex
OUTPUT "Total attendance: ", Total

Accepted values are twelve, eighteen, zero and thirty, giving total sixty. Thirty-one is replaced by eighteen within class two. There are four outer iterations, five input attempts and five inner-body executions overall.

FOR fits the four required class values. REPEAT fits a required first response followed by an unknown number of retries. Accumulation follows acceptance, so rejected values never enter the total.

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.4 Choosing and Comparing Loop Types is coming soon. Complete the matching task and written questions in your exercise book.