9618/21/M/J/22 question 7: worked solution (May/June 2022, paper 21)
Show as plain textHide plain text
Cambridge AS Level Computer Science 9618 · 11.3 Structured Programming Worked solution from the Programming Paper 2 Problem-solving and Programming booklet, Part 3 of 3. Q68 9618/21/M/J/22 original Q7 Structured · 11 marks 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. Label Text A Set OutString to "" B Is Index > LENGTH(InString)? C Is MID(InString, Index, 1) = " "? D Set OutString to OutString & MID(InString, Index, 1) E Set Index to Index + 1 F YES G NO 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 IDEA Compare characters from both ends moving inwards, in the same case, and stop at the first mismatch. TOTAL 11 marks Official mark scheme VIDEO ▶ Whole paper Video solution of the whole paper · by CS BY AQIB KHAN. Tap the picture to open it on YouTube.