Programming Constructs and Operators: Question 10
Syllabus 8.1
A firework display uses a digital countdown board. This pseudocode counts down from 15 to 3 in steps of 3, displaying each number and totalling how many numbers are displayed.
01 DECLARE Count : INTEGER
02 DECLARE Displays : INTEGER
03 Displays ← 0
04 FOR Count ← 15 TO 3 STEP -3
05 OUTPUT Count
06 Displays ← Displays + 1
07 NEXT Count
08 OUTPUT Displays
(a) State the value of Count on the first pass of this loop, and the value of Count on the
final pass of this loop. [2]
(b) Complete a trace table showing the value of Count and Displays after each pass of the
loop. [4]
(c) A technician changes line 04 to FOR Count ← 15 TO 3 STEP -4. State the sequence of values
output for Count, and the final value of Displays, for this modified loop, showing your
working. [2]
Show worked solution Hide worked solution
Worked solution
Part (a): First and final values of Count
For a FOR loop with a negative STEP, Count starts at the given start value and decreases by
the step size on each pass, continuing only while Count is still greater than or equal to the
end value.
- First pass:
Countis assigned its starting value directly from line 04, soCount = 15. - Final pass:
Countdecreases by 3 each time (15, 12, 9, 6, 3,…). The next value after 3 would be3 - 3 = 0, and since0is less than the end value3, the loop does not run again. So the final pass this loop actually executes isCount = 3.
[2 marks]: [1] for Count = 15 on the first pass, [1] for Count = 3 on the final
pass.
Part (b): Tracing the FOR loop
Displays starts at 0 (line 03). Each pass outputs the current value of Count, then adds 1 to
Displays.
| Pass | Count | OUTPUT | Displays |
|---|---|---|---|
| 1 | 15 | 15 | 1 |
| 2 | 12 | 12 | 2 |
| 3 | 9 | 9 | 3 |
| 4 | 6 | 6 | 4 |
| 5 | 3 | 3 | 5 |
After pass 5, the next value of Count would be 3 - 3 = 0, which is less than the end value 3,
so the loop stops. Line 08 then outputs the final value of Displays.
[4 marks]: [1] for the correct decreasing sequence of Count values (15, 12, 9, 6, 3),
[1] for correctly stopping the loop after Count = 3 rather than continuing to 0 or below,
[1] for a correctly incrementing Displays column, [1] for the correct final value
Displays = 5.
Part (c): Changing STEP to -4
With FOR Count ← 15 TO 3 STEP -4, Count now decreases by 4 each pass instead of 3:
- Pass 1:
Count = 15(15 >= 3, runs) - Pass 2:
Count = 15 - 4 = 11(11 >= 3, runs) - Pass 3:
Count = 11 - 4 = 7(7 >= 3, runs) - Pass 4:
Count = 7 - 4 = 3(3 >= 3, runs) - Next value:
Count = 3 - 4 = -1(-1 < 3, loop stops)
So Count takes the values 15, 11, 7, 3, in that order, 4 passes in total, so:
Displays = 4
[2 marks]: [1] for the correct sequence 15, 11, 7, 3, [1] for the correct final
value Displays = 4.
Final answers
- (a)
Count = 15on the first pass;Count = 3on the final pass. - (b) Trace as shown above.
Counttakes 15, 12, 9, 6, 3;Displaysends at 5. - (c)
Counttakes 15, 11, 7, 3;Displays = 4.