Learn
8.1.4C.1 | COUNT-CONTROLLED LOOPS: FOR
01 | WHY WRITE THE SAME INSTRUCTION AGAIN?
A program needs to display Welcome three times. You could write three OUTPUT instructions, but what if the task changes to thirty messages? Repeated copies make the algorithm longer and harder to update.
Iteration means repeating instructions. The loop body is the instruction or group of instructions inside a loop that is repeated. Think of it as the job the loop does on each pass.
A count-controlled loop repeats that job a number of times determined by its counter values and bounds. One execution of the whole body is called one iteration.
Use a FOR loop when the repetition can be determined before that loop runs, such as processing five scores or visiting a specified number of records.
The count need not be a literal written into the code. It may come from a previously supplied valid value. What matters is that the loop has defined count-controlled bounds rather than waiting for an unpredictable event.
02 | READ THE BASIC FOR FORMAT
Cambridge pseudocode uses FOR, an INTEGER counter and a matching NEXT.
DECLARE Counter : INTEGER
FOR Counter ← 1 TO 3
OUTPUT "Welcome"
NEXT CounterWhere is the body? In this example, the indented OUTPUT "Welcome" instruction is the entire loop body. It sits between the FOR header and NEXT Counter. The header controls repetition; NEXT marks where the repeated instructions end. Neither is part of the body.
The body can contain one instruction or several. If a prompt, INPUT and calculation all sit between FOR and NEXT, all three repeat in order on every iteration. Statements before FOR or after NEXT are outside that body.
| Part | Role |
|---|---|
| Counter | INTEGER variable receiving the loop’s counter values |
| 1 | Starting value |
| 3 | Final bound |
| OUTPUT "Welcome" | Loop body: the instruction repeated on every iteration |
| NEXT Counter | Closes this FOR loop and identifies its counter |
The body runs after each counter value is assigned. Welcome is output three times. Indentation shows which statements belong inside the loop.
NEXT does not mean another input from a user. It is part of the loop structure that progresses through the counter values.
03 | THE ENDPOINTS ARE INCLUDED
In the default upward loop, the counter increases by one. Both start and end are included when that sequence reaches them.
| Header | Counter values in the body | Iterations |
|---|---|---|
| FOR Counter ← 1 TO 3 | 1, 2, 3 | 3 |
| FOR Counter ← 2 TO 5 | 2, 3, 4, 5 | 4 |
| FOR Counter ← 5 TO 5 | 5 | 1 |
| FOR Counter ← 5 TO 3 | None with the default positive step | 0 |
For an upward default loop with start no greater than end, the count is end minus start plus one. From two to five, that is five minus two plus one, or four.
Do not assume the final bound alone tells you the number of repetitions. A loop ending at five may run four times if it starts at two.
A default loop with its start above its end executes zero times. It does not automatically reverse direction.
04 | YOU CAN USE THE COUNTER IN THE BODY
The counter is available to the repeated instructions, so each iteration can use a different number.
DECLARE Counter : INTEGER
FOR Counter ← 1 TO 3
OUTPUT "Round: ", Counter
NEXT CounterThe output events are Round: 1, Round: 2 and Round: 3. The same OUTPUT instruction reads a different current counter value on each iteration.
The FOR structure supplies the counter’s progression. Do not also add Counter ← Counter + 1 inside this body as though it were a WHILE loop; that would interfere with the intended counter control.
Choose a descriptive name such as StudentIndex or RoundNumber when it helps communicate the repeated job.
05 | DISTINGUISH SETUP, BODY AND FINAL CODE
Only statements between FOR and its matching NEXT form the repeated body. Statements before and after it have different roles.
DECLARE Counter : INTEGER
OUTPUT "Starting"
FOR Counter ← 1 TO 3
OUTPUT "Round: ", Counter
NEXT Counter
OUTPUT "Finished"Starting appears once, followed by three round messages, then Finished once. There are five OUTPUT executions overall.
If Finished were placed inside the body, it would appear three times. Moving a statement changes its repetition, even if its text is unchanged.
Record the counter values during body execution. Do not assume an implementation-specific counter value after NEXT unless the question defines it; these algorithms do not use that value afterwards.
06 | BUILD A RUNNING TOTAL
A loop can repeat processing rather than only output. Initialise a total once, then add the current counter on each iteration.
DECLARE Counter : INTEGER
DECLARE Total : INTEGER
Total ← 0
FOR Counter ← 1 TO 3
Total ← Total + Counter
NEXT Counter
OUTPUT "Total: ", Total| Body execution | Counter | Total before addition | Total afterwards |
|---|---|---|---|
| 1 | 1 | 0 | 1 |
| 2 | 2 | 1 | 3 |
| 3 | 3 | 3 | 6 |
The counter tells you which iteration is running; Total stores the accumulated sum. They are separate variables with separate jobs.
If Total ← 0 were inside the body, earlier additions would be discarded. Setup belongs before the loop when it must apply to the whole accumulation.
07 | STEP THROUGH THE ITERATIONS
Predict the new Total before moving to the next iteration. The demo follows the running-total example above.
COUNTER IN THE BODY
Not startedTOTAL
0Setup complete: Total is zero.
No final output yet.
The final step displays Total after the loop. The counter panel describes the last body iteration rather than claiming a particular post-loop counter value.
08 | RECEIVE ONE INPUT PER ITERATION
Suppose a task requires three valid numeric scores and their total. A FOR loop receives one score on each pass.
DECLARE StudentIndex : INTEGER
DECLARE Score : INTEGER
DECLARE Total : INTEGER
Total ← 0
FOR StudentIndex ← 1 TO 3
OUTPUT "Enter score for student ", StudentIndex
INPUT Score
Total ← Total + Score
NEXT StudentIndex
OUTPUT "Total score: ", TotalAssume every input is a valid whole-number score. Inputs four, seven and two make Total four, eleven and thirteen. The prompt and INPUT execute three times, while the final total output executes once.
Score is reused for the current input. Earlier individual scores are not preserved, but their contribution remains in Total.
This algorithm receives three scores; it does not check a range. If validation is required, it needs suitable additional logic.
09 | A PREVIOUS INPUT CAN SET THE LOOP COUNT
You do not have to know the count when writing the algorithm. Receive a valid non-negative whole-number StudentCount first, then use it as a bound.
DECLARE StudentCount : INTEGER
DECLARE StudentIndex : INTEGER
OUTPUT "Enter the number of students"
INPUT StudentCount
FOR StudentIndex ← 1 TO StudentCount
OUTPUT "Processing student ", StudentIndex
NEXT StudentIndexWith StudentCount four, the body runs for one, two, three and four. With zero, the default loop runs from one to zero and executes no body instructions.
The bound must be available when the loop begins. Prompting for StudentCount after the header would be too late for this structure.
In these examples, the count is determined before repetition. An instruction such as “keep asking until the user supplies an accepted value” does not provide a known number of attempts; a condition-controlled loop is more suitable for that job.
10 | STEP CHANGES THE COUNTER INCREMENT
STEP specifies a different integer increment. Positive steps greater than one can skip values.
DECLARE Counter : INTEGER
FOR Counter ← 1 TO 6 STEP 2
OUTPUT Counter
NEXT CounterThe body counter values are one, three and five. The next candidate would be seven, beyond six, so it does not get a body execution. Six is not output because the sequence of steps never reaches it.
| Header | Body counter values | Iterations |
|---|---|---|
| 1 TO 5 STEP 2 | 1, 3, 5 | 3 |
| 1 TO 6 STEP 2 | 1, 3, 5 | 3 |
| 2 TO 8 STEP 3 | 2, 5, 8 | 3 |
Do not use end minus start plus one for a non-unit step. List the values carefully or use reasoning that accounts for the increment.
A zero step does not progress towards completion. Use a suitable non-zero integer step for these count-controlled examples.
11 | COUNT DOWN WITH A NEGATIVE STEP
To move downwards, specify a negative increment and appropriate bounds.
DECLARE Counter : INTEGER
FOR Counter ← 5 TO 1 STEP -2
OUTPUT Counter
NEXT CounterThe body receives five, three and one. The next candidate would be minus one, beyond the lower end in the chosen direction, so the loop is complete.
A countdown from three to one with STEP -1 outputs three, two and one. Without the negative STEP, that header would use the default positive direction and execute zero times.
Check both direction and bounds. An increment must move the counter through the intended values; changing the sign changes the progression.
12 | NEST A FOR LOOP FOR REPEATED GROUPS
A nested loop is a loop inside another loop. Consider two rows, each containing three seat positions.
DECLARE Row : INTEGER
DECLARE Seat : INTEGER
FOR Row ← 1 TO 2
FOR Seat ← 1 TO 3
OUTPUT "Row ", Row, ", seat ", Seat
NEXT Seat
NEXT RowFor row one, the inner loop outputs seats one, two and three. The outer loop then advances to row two, and a fresh inner loop again runs seats one, two and three.
| Outer Row | Inner Seat values | Pairs output |
|---|---|---|
| 1 | 1, 2, 3 | (1,1), (1,2), (1,3) |
| 2 | 1, 2, 3 | (2,1), (2,2), (2,3) |
Use separate counters and match NEXT Seat to the inner loop and NEXT Row to the outer loop. The inner loop completes for each outer iteration.
The multiplication rule works here because each outer iteration runs the same three inner iterations. More complex bounds can require a different count.
13 | TEST THE BOUNDS AND THE REPEATED WORK
Check a normal loop, a single-iteration loop and a zero-iteration default loop. These reveal mistaken assumptions about including the endpoint or always executing once.
For input-count loops, verify the number of prompts, number of supplied values, calculations inside the body and final outputs outside it.
For STEP, test a bound exactly reached and one not reached. A one-to-six step-two loop exposes an algorithm that incorrectly forces the end value into the output.
For a running total, choose values that show accumulation rather than only the final input. Four, seven and two should total thirteen, not two.
14 | COMMON LOOP MISTAKES
Missing an endpoint: the basic upward FOR includes both specified endpoints.
End bound mistaken for iteration count: start two and end five gives four iterations.
Extra counter update in the body: the FOR already controls its progression.
Total reset inside the body: accumulated earlier values are lost.
Final output placed inside: it repeats instead of appearing once after processing.
Countdown without negative STEP: the default positive loop does not automatically reverse.
Nested counters confused: the inner counter starts its defined sequence again for each outer iteration.
FOR used for an unknown number of retries: choose a condition-controlled structure when stopping depends on an unpredictable event.
15 | EXPLAIN THE REPETITION CLEARLY
A useful explanation is: “The counter receives one, two and three, so the body runs three times. Total is initialised before the loop and updated inside it, therefore each iteration adds to the earlier sum. The final output is after NEXT, so it appears once.”
For nested repetition: “Each of two rows runs a fresh three-seat inner loop, resulting in six seat outputs overall.”
When tracing, record each body counter value and the state changes in that body. Keep setup, repeated processing and final code separate.
The next lesson introduces WHILE, a pre-condition loop used when a condition controls whether repetition should continue.