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
| Feature | FOR | WHILE | REPEAT UNTIL |
|---|---|---|---|
| Main control | Counter progression and bounds | Boolean continuation condition | Boolean stopping condition |
| First body | Only if progression has an applicable value | Only if the first condition is true | Before the first stopping check |
| True condition | Not expressed as a WHILE-style Boolean header | Continue into the body | Stop after the body |
| Minimum body executions | Can be zero | Can be zero | At least one when reached |
| Progress | Counter increment provided by FOR | Updates/inputs specified by the algorithm | Updates/inputs specified by the algorithm |
| Typical use | Defined count of items | Possibly empty condition-controlled processing | Receive 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 TotalAssume 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 TotalAssume 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: ", ScoreAssume 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 > 3FOR 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.
| Target N | FOR outputs | WHILE outputs | Naive REPEAT outputs |
|---|---|---|---|
| 3 | 1, 2, 3 | 1, 2, 3 | 1, 2, 3 |
| 1 | 1 | 1 | 1 |
| 0 | None | None | 1 |
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.
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 <= 10WHILE 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 TotalWith 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 TotalAssume 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.