Worked solution from the Algorithm Design and Problem-solving Paper 2 Problem-solving and Programming booklet, Part 2 of 2.
The loop runs a known number of times (I goes from 2 to 4), so a count-controlled loop (FOR ... NEXT) is better than WHILE.
Loop structure: count-controlled (FOR loop) [1]
Justification: the number of iterations is known before the loop starts [1]
Dry run the algorithm one line at a time. Write a new row each time a value changes:
| I | Key | J | Chars[J] | Chars[1] | Chars[2] | Chars[3] | Chars[4] |
|---|---|---|---|---|---|---|---|
| 2 | 'D' | 'T' | 'H' | 'R' | |||
| 'T' | 1 | 'D' | |||||
| 3 | |||||||
| 'H' | 2 | 'T' | 'T' | ||||
| 1 | 'D' | 'H' | |||||
| 4 | |||||||
| 'R' | 3 | 'T' | 'T' | ||||
| 2 | 'H' | 'R' | |||||
| 5 |
Row with Key = 'T' and J = 1 and Chars[J] = 'D' correct [1]
Row with Key = 'H', J = 2, Chars[J] = 'T' and Chars[3] = 'T' correct [1]
Row with J = 1, Chars[J] = 'D' and Chars[2] = 'H' correct [1]
Rows with Key = 'R', J = 3 then 2 and the changes to Chars[4] = 'T' and Chars[3] = 'R' correct [1]
I column correct: 2, 3, 4, 5 [1]
Final array: 'D', 'H', 'R', 'T' [1]
▶ Whole paper
Video solution of the whole paper · by Sir Sikandar Raza. Tap the picture to open it on YouTube.
Solutions follow the official Cambridge mark schemes; marks are shown in grey. Videos are from other YouTube channels. Paper codes read component / series / year: M/J = May/June, O/N = October/November. Past-paper questions © UCLES, reproduced for classroom practice.