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...NEXTloops. - 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.
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.
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.
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 |
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 |
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
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
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.
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
| Current value | Add the step | Next value |
|---|---|---|
| 2 | +3 | 5 |
| 5 | +3 | 8 |
| 8 | +3 | 11 |
| 11 | +3 | 14 |
| 14 | +3 | 17 |
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"
| 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 |
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:
Example
FOR Cycle β 4 TO 10
OUTPUT Cycle
NEXT Cycle
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
The loop executes four times. The next value, 25, would exceed 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
- Write the first control-variable value.
- Execute every statement in the loop body in order.
- Record assignments and output.
- Apply the step to obtain the next control-variable value.
- Check whether the next value is still within the loop bounds.
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.
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 |
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"
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 |
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 |
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.
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
FORstructure 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 withNEXT 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:
FOR X β 1 TO 12FOR X β 5 TO 15 STEP 5FOR X β 20 TO 8 STEP -3FOR 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
- 12 iterations
- 3 iterations: 5, 10, 15
- 5 iterations: 20, 17, 14, 11, 8
- 3 iterations: 2, 7, 12
Question 5
Value |
Output |
|---|---|
| 2 | 4 |
| 4 | 16 |
| 6 | 36 |
| 8 | 64 |
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 |