A-Level Computer Science / Unit 11: Structured Programming

11.2.3 Count-Controlled Repetition

πŸ”’ Lesson slides are available to signed-in users. Sign in

11.2.3 Count-Controlled Repetition

Repetition allows the same block of statements to execute several times. A count-controlled loop is used when the required number of repetitions can be determined before the loop begins.

In pseudocode, this form of repetition is written using FOR and NEXT. A control variable follows a defined sequence from a starting value towards an ending value.

By the end of this section, you should be able to:

  • Explain when count-controlled repetition is appropriate.
  • Identify the control variable, start value, end value and step.
  • Write ascending and descending FOR...NEXT loops.
  • Explain that the pseudocode end value is included when it is reached.
  • Determine the sequence of values taken by the control variable.
  • Calculate or trace the number of loop iterations.
  • Use a count-controlled loop to produce output or process repeated input.
  • Use an accumulator to form a running total.
  • Distinguish statements that belong inside the loop from statements that run once outside it.
  • Recognise off-by-one errors and incompatible loop bounds.
Scope of this page: conditional repetition is developed on the next two pages. Here, the controlling sequence and number of possible repetitions are established before execution begins.

Count-Controlled Repetition

Iteration means executing a block of statements repeatedly. In a count-controlled loop, repetition is governed by a sequence of values assigned to a control variable.

Iteration: repeated execution of a statement or block of statements.
Count-controlled loop: a loop whose repetitions are governed by a known sequence of control-variable values.

Original example: six inspection stations

FOR StationNumber ← 1 TO 6
    OUTPUT "Inspect station ", StationNumber
NEXT StationNumber

The body executes six times because the control variable takes the values 1, 2, 3, 4, 5 and 6.

Common misconception: a count-controlled loop is not limited to displaying its counter. The repeated block may contain input, assignments, calculations, selection or calls to routines.

The FOR...NEXT Structure

General pseudocode pattern

FOR <ControlVariable> ← <StartValue> TO <EndValue> STEP <StepValue>
    <Statement or statements>
NEXT <ControlVariable>

The STEP part may be omitted when the control variable should increase by 1.

FOR Attempt ← 1 TO 4
    OUTPUT Attempt
NEXT Attempt

This is equivalent to:

FOR Attempt ← 1 TO 4 STEP 1
    OUTPUT Attempt
NEXT Attempt
Part Purpose Example
Control variable Stores the current value in the loop sequence Attempt
Start value Provides the first control-variable value 1
End value Identifies the final permitted value 4
Step value States how the control variable changes 1
Loop body Contains the statements repeated for each value OUTPUT Attempt
NEXT Ends the body and advances the loop NEXT Attempt
Use the same identifier after FOR and NEXT. This becomes especially important when loops are nested.

The Control Variable

The control variable holds the current value in the count sequence. At the start of each iteration, its value can be used by the statements inside the loop.

Example: creating shelf labels

FOR ShelfNumber ← 3 TO 7
    OUTPUT "SHELF-", ShelfNumber
NEXT ShelfNumber
Iteration ShelfNumber Output
1 3 SHELF-3
2 4 SHELF-4
3 5 SHELF-5
4 6 SHELF-6
5 7 SHELF-7
Common mistake: do not normally assign a new value to the control variable inside the loop body. The FOR structure already controls its progression.

The End Value Is Inclusive

A pseudocode FOR loop includes the end value when the step sequence reaches it.

FOR Batch ← 2 TO 6
    OUTPUT Batch
NEXT Batch
2, 3, 4, 5, 6

There are five iterations, not four. Both the start value and end value appear in the sequence.

When the end value is not reached exactly

FOR Checkpoint ← 2 TO 13 STEP 4
    OUTPUT Checkpoint
NEXT Checkpoint
2, 6, 10

The next value would be 14, which is beyond the end value. The value 13 is not produced because it does not occur in the sequence.

Common misconception: β€œthe end is included” does not mean that the loop changes its step to land on the end value. The end appears only when the regular step sequence reaches it.

Changing the STEP Value

A step larger than 1 allows the control variable to move through a spaced sequence.

Original example: checking every third storage bay

FOR BayNumber ← 2 TO 17 STEP 3
    OUTPUT "Check bay ", BayNumber
NEXT BayNumber
2, 5, 8, 11, 14, 17
Current value Add the step Next value
2 +3 5
5 +3 8
8 +3 11
11 +3 14
14 +3 17
To trace a custom step, begin with the start value and repeatedly add the step. Stop before using a value beyond the permitted end.

Counting Down

A negative step produces a descending sequence. The start value must normally be greater than the end value.

Original example: staged shutdown

FOR Countdown ← 9 TO 1 STEP -2
    OUTPUT Countdown
NEXT Countdown

OUTPUT "System isolated"
9, 7, 5, 3, 1
Step direction Typical relationship Example
Positive Start value is less than or equal to the end value 2 TO 10 STEP 2
Negative Start value is greater than or equal to the end value 9 TO 1 STEP -2
Direction error: the loop FOR Number ← 1 TO 8 STEP -1 cannot progress from 1 towards 8. Its bounds and step direction are incompatible.

Determining the Number of Iterations

For a step of 1, an ascending loop from StartValue to EndValue executes:

EndValue - StartValue + 1 times

Example

FOR Cycle ← 4 TO 10
    OUTPUT Cycle
NEXT Cycle
10 - 4 + 1 = 7 iterations

The control-variable values are 4, 5, 6, 7, 8, 9 and 10.

For other step values

Construct the sequence carefully or repeatedly apply the step until the next value would pass the end.

FOR Position ← 5 TO 24 STEP 5
    OUTPUT Position
NEXT Position
5, 10, 15, 20

The loop executes four times. The next value, 25, would exceed the end value.

Listing the control-variable sequence is often the safest method when the step is not 1 or when the sequence does not land exactly on the end value.

Tracing a Count-Controlled Loop

A trace table should contain one row for each execution of the loop body.

Original example

FOR Number ← 3 TO 9 STEP 2
    Result ← Number * 4
    OUTPUT Result
NEXT Number
Iteration Number Result ← Number * 4 Output
1 3 12 12
2 5 20 20
3 7 28 28
4 9 36 36

Reliable tracing process

  1. Write the first control-variable value.
  2. Execute every statement in the loop body in order.
  3. Record assignments and output.
  4. Apply the step to obtain the next control-variable value.
  5. Check whether the next value is still within the loop bounds.
Do not add an extra trace-table row for the first value outside the bounds. That value causes the loop to stop; the body does not execute for it.

Using a Running Total

An accumulator stores a value that is updated during each iteration. A running total must be initialised before the loop begins.

Accumulator: a variable used to collect a combined result across several iterations.

Original example: weekly energy readings

DECLARE Day : INTEGER
DECLARE EnergyUsed : REAL
DECLARE TotalEnergy : REAL

TotalEnergy ← 0

FOR Day ← 1 TO 5
    OUTPUT "Enter the energy used on day ", Day, ": "
    INPUT EnergyUsed

    TotalEnergy ← TotalEnergy + EnergyUsed
NEXT Day

OUTPUT "Total energy used: ", TotalEnergy

TotalEnergy is initialised once, before repetition. Each new reading is then added to the value already stored.

Example trace

Day Input Total before update Total after update
1 8.5 0.0 8.5
2 7.2 8.5 15.7
3 9.1 15.7 24.8
Common mistake: placing TotalEnergy ← 0 inside the loop resets the accumulated value on every iteration.

Statements Inside and Outside the Loop

Indentation and placement determine how often a statement executes.

Position Typical purpose Frequency
Before FOR Initialise an accumulator or prepare fixed data Once
Between FOR and NEXT Perform the repeated processing Once per iteration
After NEXT Use the completed result Once after repetition

Compare the two algorithms

Output during every iteration

FOR Item ← 1 TO 4
    OUTPUT "Processing item ", Item
NEXT Item

Output once after all iterations

FOR Item ← 1 TO 4
    OUTPUT "Processing item ", Item
NEXT Item

OUTPUT "All items processed"
Moving a statement across NEXT changes how many times it runs.

When Is a FOR Loop Suitable?

A count-controlled loop is suitable when the number of repetitions or the complete sequence of control values is known before the loop starts.

Situation FOR suitable? Reason
Produce labels for lockers 1 to 40 Yes The required sequence is known
Input exactly eight test readings Yes The number of inputs is fixed
Output multiples of 5 from 5 to 50 Yes The start, end and step are known
Keep requesting a password until it is correct No The number of attempts is not known in advance
Process records until an end marker is found Usually no Repetition depends on a condition rather than a fixed count
To justify a FOR loop, state what makes the count or control sequence known before repetition begins.

Worked Example: Calibration Test Results

A technician enters six calibration readings. The algorithm must calculate the total, count how many readings are at least 75, and calculate the average.

Pseudocode

DECLARE TestNumber : INTEGER
DECLARE Reading : REAL
DECLARE TotalReading : REAL
DECLARE PassedCount : INTEGER
DECLARE AverageReading : REAL

TotalReading ← 0
PassedCount ← 0

FOR TestNumber ← 1 TO 6
    OUTPUT "Enter reading ", TestNumber, ": "
    INPUT Reading

    TotalReading ← TotalReading + Reading

    IF Reading >= 75
    THEN
        PassedCount ← PassedCount + 1
    ENDIF
NEXT TestNumber

AverageReading ← TotalReading / 6

OUTPUT "Total: ", TotalReading
OUTPUT "Average: ", AverageReading
OUTPUT "Readings at or above 75: ", PassedCount

Why a FOR loop is appropriate

Exactly six readings must be entered, so the number of loop-body executions is known before the loop begins.

Partial trace

Test Reading Total after update Reading >= 75 PassedCount
1 81 81 TRUE 1
2 69 150 FALSE 1
3 77 227 TRUE 2
Initialise both accumulators before the loop. Calculate the average after the complete total has been formed.

Interactive: Count-Controlled Loop Tracer

Select a scenario, adjust the bounds and trace the control variable one iteration at a time. The widget also identifies loops whose bounds and step direction are incompatible.

Output sequence

Output each value taken by the control variable.

The loop produces five control-variable values.

FOR Counter ← 2 TO 6
    OUTPUT Counter
NEXT Counter

Trace

Current output: --
Iteration count: 0
Current control value: Not started

Step 1

Initialise the loop

The control variable receives the start value before the first execution of the body.

Change the step to a negative value and reverse the bounds to investigate a descending count.

Common Mistakes and Misconceptions

  • Excluding the end value: the end is included when the step sequence reaches it.
  • Forcing the loop to reach the end: the regular step is not changed to land on the final value.
  • Using a zero step: the control variable would not progress through a sequence.
  • Using the wrong direction: a negative step cannot progress from a smaller start towards a larger end.
  • Adding an extra iteration: the first value outside the bounds stops the loop and does not execute the body.
  • Changing the control variable manually: the FOR structure should manage it.
  • Initialising an accumulator inside the loop: this removes the result formed during earlier iterations.
  • Placing final output inside the loop: this may display an incomplete result during every iteration.
  • Using FOR for an unknown number of repeats: a conditional loop is usually more appropriate.
  • Mismatching the control variable: FOR Day... should close with NEXT Day.

Practice

Question 1: basic sequence

Write the values output by:

FOR Number ← 4 TO 9
    OUTPUT Number
NEXT Number

Question 2: custom step

Write the values output by:

FOR Position ← 3 TO 22 STEP 4
    OUTPUT Position
NEXT Position

Question 3: descending sequence

Write pseudocode that outputs:

18, 15, 12, 9, 6, 3

Question 4: number of iterations

State how many times each body executes:

  1. FOR X ← 1 TO 12
  2. FOR X ← 5 TO 15 STEP 5
  3. FOR X ← 20 TO 8 STEP -3
  4. FOR X ← 2 TO 14 STEP 5

Question 5: trace an expression

FOR Value ← 2 TO 8 STEP 2
    OUTPUT Value ^ 2
NEXT Value

Create a trace table showing Value and the output.

Question 6: repeated input

Write pseudocode that receives exactly seven temperature readings and outputs each reading immediately after it is entered.

Question 7: running total

Write pseudocode that inputs four package masses and displays their total mass after all four values have been entered.

Question 8: locate the placement error

FOR Day ← 1 TO 5
    TotalVisitors ← 0
    INPUT Visitors
    TotalVisitors ← TotalVisitors + Visitors
NEXT Day

OUTPUT TotalVisitors

Explain the error and rewrite the algorithm correctly.

Question 9: compatible bounds

Explain the problem with:

FOR Number ← 2 TO 12 STEP -2
    OUTPUT Number
NEXT Number

Question 10: justify the loop

A system must create one identifier for each of 32 storage containers. Explain why count-controlled repetition is appropriate.

Show suggested answers

Question 1

4, 5, 6, 7, 8, 9

Question 2

3, 7, 11, 15, 19

The next value would be 23, which exceeds the end value.

Question 3

FOR Number ← 18 TO 3 STEP -3
    OUTPUT Number
NEXT Number

Question 4

  1. 12 iterations
  2. 3 iterations: 5, 10, 15
  3. 5 iterations: 20, 17, 14, 11, 8
  4. 3 iterations: 2, 7, 12

Question 5

Value Output
24
416
636
864

Question 6

DECLARE ReadingNumber : INTEGER
DECLARE Temperature : REAL

FOR ReadingNumber ← 1 TO 7
    OUTPUT "Enter reading ", ReadingNumber, ": "
    INPUT Temperature
    OUTPUT "Recorded temperature: ", Temperature
NEXT ReadingNumber

Question 7

DECLARE PackageNumber : INTEGER
DECLARE PackageMass : REAL
DECLARE TotalMass : REAL

TotalMass ← 0

FOR PackageNumber ← 1 TO 4
    INPUT PackageMass
    TotalMass ← TotalMass + PackageMass
NEXT PackageNumber

OUTPUT "Total mass: ", TotalMass

Question 8

The total is reset to zero during every iteration. It must be initialised once before the loop.

TotalVisitors ← 0

FOR Day ← 1 TO 5
    INPUT Visitors
    TotalVisitors ← TotalVisitors + Visitors
NEXT Day

OUTPUT TotalVisitors

Question 9

The negative step moves downwards, but the loop must progress from 2 towards the larger end value 12. The direction is incompatible. Use a positive step or reverse the bounds.

Question 10

The required number of repetitions is known before the loop starts: exactly 32 identifiers must be created.

Review

Concept Key idea Example
Count-controlled loop Uses a known sequence of control values FOR X ← 1 TO 8
Control variable Stores the current value in the sequence X
Start value The first value used 1
End value The final permitted value, when reached 8
Step The change applied after each iteration STEP 2
Accumulator Stores a running result across iterations Total ← Total + Value
NEXT Ends the body and advances the count NEXT X
Final exam tip: identify the complete control-variable sequence first. Then create one trace-table row for each value in that sequence and execute the loop body in order.