Cambridge AS Level Computer Science 9618 · 9.2 Algorithms

Q39 · 9618/21/M/J/25 Q4

Worked solution from the Algorithm Design and Problem-solving Paper 2 Problem-solving and Programming booklet, Part 2 of 2.

Q399618/21/M/J/25original Q4Structured · 8 marks
Question 4 from 9618/21/M/J/25

Worked solution

(a)

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]

(b)

Dry run the algorithm one line at a time. Write a new row each time a value changes:

IKeyJChars[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]

KEY IDEAIn a trace table, write a new row each time a value changes and follow the inner loop until its condition is false.
TOTAL 8 marks

Official mark scheme

Mark scheme for 9618/21/M/J/25 question 4
VIDEO
▶ 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.