Cambridge A2 Level Computer Science 9618 · 19.1 Algorithms

Q22 · 9618/31/O/N/25 Q9

Worked solution from the Computational thinking and Problem-solving Paper 3 Advanced Theory booklet, Part 1 of 2.

Q229618/31/O/N/25original Q9Structured · 9 marks
Question 9 from 9618/31/O/N/25

Worked solution

(a)(i)

Pop returns a string. It can remove only if the stack is not empty, so Top must be at least 0. Take the item at Top, then lower Top, and return the item.

FUNCTION Pop() RETURNS STRING
    DECLARE DataItem : STRING
    DataItem ← ""
    IF Top > -1 THEN
        DataItem ← StackArray[Top]
        Top ← Top - 1
    ELSE
        DataItem ← "You cannot remove data; the stack is empty"
    ENDIF
    RETURN DataItem
ENDFUNCTION

RETURNS STRING [1]

IF Top > -1 THEN (or Top >= Base) [1]

DataItem ← StackArray[Top] [1]

Top ← Top - 1 [1]

RETURN DataItem [1]

(a)(ii)

Call the function inside the OUTPUT.

OUTPUT "The data removed from the stack is ", Pop()

OUTPUT with a suitable message and the value returned by Pop() [1]

(b)

Write the three features.

A recursive algorithm calls itself (it has a general case) [1]

It has a base case (a stopping condition) [1]

It changes its state so that each call moves towards the base case [1]

KEY IDEAPop removes the top item only if the stack is not empty; recursion needs a self-call, a base case and progress towards it.
TOTAL 9 marks

Official mark scheme

Mark scheme for 9618/31/O/N/25 question 9
VIDEO
▶ Whole paper

Video solution of the whole paper · by Zafar Ali Khan (ZAK). 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.