Cambridge AS Level Computer Science 9618 · 11.3 Structured Programming

Q68 · 9618/21/M/J/22 Q7

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

Q689618/21/M/J/22original Q7Structured · 11 marks
Question 7 from 9618/21/M/J/22

Worked solution

(a)

Compare the first character with the last, the second with the second last, and so on. Only half the string needs checking. Change both characters to the same case before comparing.

FUNCTION IsPalindrome(InString : STRING) RETURNS BOOLEAN
    DECLARE IsPal : BOOLEAN
    DECLARE Index, Num : INTEGER
    DECLARE CharA, CharB : CHAR
    IsPal ← TRUE
    Index ← 1
    Num ← INT(LENGTH(InString) / 2)
    WHILE Index <= Num AND IsPal = TRUE
        CharA ← MID(InString, Index, 1)
        CharB ← MID(InString, LENGTH(InString) - Index + 1, 1)
        IF UCASE(CharA) <> UCASE(CharB) THEN
            IsPal ← FALSE
        ENDIF
        Index ← Index + 1
    ENDWHILE
    RETURN IsPal
ENDFUNCTION

Function header with the string parameter, ending and BOOLEAN return type [1]

Work out the number of pairs to compare (half the length) [1]

A loop over half (or all) of the string [1]

Extract the two characters to compare (or build the reversed string) [1]

Convert both characters to the same case, for example UCASE [1]

Test for a mismatch inside the loop (or compare with the reversed string after it) [1]

Return TRUE or FALSE correctly in both cases [1]

(b)

Follow the flowchart: A sets OutString, B ends the loop at the end of the string, C tests for a space, D adds a non-space character to OutString.

LabelText
ASet OutString to ""
BIs Index > LENGTH(InString)?
CIs MID(InString, Index, 1) = " "?
DSet OutString to OutString & MID(InString, Index, 1)
ESet Index to Index + 1
FYES
GNO

Label B correct [1]

Label C correct [1]

Label D correct [1]

F = YES and G = NO (the space test on C must be sensible) [1]

KEY IDEACompare characters from both ends moving inwards, in the same case, and stop at the first mismatch.
TOTAL 11 marks

Official mark scheme

Mark scheme for 9618/21/M/J/22 question 7
VIDEO
▶ Whole paper

Video solution of the whole paper · by CS BY AQIB KHAN. 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.