CIE IGCSE | 8.1.4C.1 Count-Controlled Loops: FOR

Lesson objective

Use count-controlled FOR loops, trace counter values and repeated instructions, calculate iteration counts and apply STEP and simple nested loops.

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 Counter

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

Counter receives one, two and three for the three body executions
PartRole
CounterINTEGER variable receiving the loop’s counter values
1Starting value
3Final bound
OUTPUT "Welcome"Loop body: the instruction repeated on every iteration
NEXT CounterCloses 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.

These examples use the default increment of one
HeaderCounter values in the bodyIterations
FOR Counter ← 1 TO 31, 2, 33
FOR Counter ← 2 TO 52, 3, 4, 54
FOR Counter ← 5 TO 551
FOR Counter ← 5 TO 3None with the default positive step0

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 Counter

The 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
Final output after the loop is Total: 6
Body executionCounterTotal before additionTotal afterwards
1101
2213
3336

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 started

TOTAL

0

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

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

    With 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 Counter

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

    The end bound is a limit, not a guarantee that its value appears
    HeaderBody counter valuesIterations
    1 TO 5 STEP 21, 3, 53
    1 TO 6 STEP 21, 3, 53
    2 TO 8 STEP 32, 5, 83

    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 Counter

    The 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 Row

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

    Two outer iterations times three inner iterations gives six body outputs
    Outer RowInner Seat valuesPairs output
    11, 2, 3(1,1), (1,2), (1,3)
    21, 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.

    MATCH THE LOOP COMPONENT TO ITS ROLE

    Terminology

    Terminology

    Iteration

    Repetition of instructions.

    Count-controlled loop

    Repetition determined by counter bounds and an increment.

    FOR

    Introduces a count-controlled loop in Cambridge pseudocode.

    Counter

    An INTEGER variable receiving the loop’s successive values.

    Start bound

    The first counter value in the intended progression.

    End bound

    The limit through which the counter progression is allowed.

    Loop body

    The instructions repeated on each iteration.

    NEXT

    The keyword closing a FOR loop and naming its counter.

    Inclusive endpoint

    An endpoint included if the counter progression reaches it.

    STEP

    Specifies the counter’s integer increment.

    Increment

    The amount added to advance the counter progression.

    Negative step

    An increment that moves the counter downwards.

    Setup

    Instructions executed before repetition to establish its initial state.

    Running total

    An accumulated sum updated during processing.

    Nested loop

    A loop inside another loop.

    Outer loop

    The enclosing loop in a nested arrangement.

    Inner loop

    The enclosed loop run for each applicable outer iteration.

    Zero-iteration loop

    A loop whose body does not execute for the specified bounds or conditions.

    Questions

    Questions

    CHECK YOUR UNDERSTANDING

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

    1. Which tasks suit a count-controlled FOR loop?
    2. FOR Counter ← 2 TO 5 uses the default step. Which counter values appear in the body?
    3. What happens with FOR Counter ← 5 TO 5?
    4. Which statements about body placement are correct?
    5. Where should a running Total normally be initialised?
    6. FOR Counter ← 1 TO 6 STEP 2 gives which body values?
    7. FOR Counter ← 5 TO 1 STEP -2 gives which body values?
    8. Two outer rows each run a fresh three-seat inner loop. Which are correct?

    EXPLAIN AND COMPARE

    Write your answers before revealing each sample.

    1. Define count-controlled iteration and suggest a suitable example.

    2. Show the counter values and iteration count for FOR Counter ← 2 TO 5.

    3. Explain the difference between FOR Counter ← 5 TO 5 and FOR Counter ← 5 TO 3 with default step.

    4. Trace Total initially zero with FOR Counter ← 1 TO 3 containing Total ← Total + Counter.

    5. Explain why Total ← 0 inside that body prevents a running total.

    6. State the body values for 1 TO 6 STEP 2 and explain why six is absent.

    7. Demonstrate a countdown outputting three, two and one using FOR.

    8. Explain how nested loops for two rows and three seats produce six outputs.

    BUILD IT | FIVE PRACTICE SCORES

    Receive five valid whole-number scores, with a numbered prompt for each. Calculate their total and mean, then output both once after processing. Assume valid input and no validation retry requirement. Write a complete algorithm and trace inputs two, four, six, eight and ten.

    Reveal one possible solution
    DECLARE StudentIndex : INTEGER
    DECLARE Score : INTEGER
    DECLARE Total : INTEGER
    DECLARE Average : REAL
    Total ← 0
    FOR StudentIndex ← 1 TO 5
        OUTPUT "Enter score for student ", StudentIndex
        INPUT Score
        Total ← Total + Score
    NEXT StudentIndex
    Average ← Total / 5
    OUTPUT "Total score: ", Total
    OUTPUT "Mean score: ", Average

    Total progresses through two, six, twelve, twenty and thirty. Mean is thirty divided by five, or six. There are five prompts, five INPUT executions and two final result outputs.

    Extend: change the task to four scores and identify both places that need amendment: the FOR end bound and the denominator. Alternatively define a named constant for the fixed score count and use it in both places.

    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.1 Count-Controlled Loops: FOR is coming soon. Complete the matching task and written questions in your exercise book.