Cambridge AS Level Computer Science 9618 · 11.1 Programming Basics

Q31 · 9618/23/M/J/25 Q5

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

Q319618/23/M/J/25original Q5Structured · 8 marks
Question 5 from 9618/23/M/J/25

Worked solution

Count the '1' characters one at a time. If the count is odd, add '1'; if even, add '0'.

FUNCTION Parity(BitString : STRING) RETURNS STRING
    DECLARE Index, Count : INTEGER
    Count ← 0
    FOR Index ← 1 TO LENGTH(BitString)
        IF MID(BitString, Index, 1) = '1' THEN
            Count ← Count + 1
        ENDIF
    NEXT Index
    IF Count MOD 2 = 1 THEN
        BitString ← BitString & '1'
    ELSE
        BitString ← BitString & '0'
    ENDIF
    RETURN BitString
ENDFUNCTION

Function heading with STRING parameter, RETURNS STRING and ENDFUNCTION [1]

Loop for the length of BitString [1]

Current character extracted inside the loop (MID) [1]

Character compared with '1' (or '0') inside the loop [1]

Count increased inside the loop, and set to 0 before it [1]

Test for an even or odd number of 1s (MOD 2) [1]

'1' or '0' appended as needed with & [1]

Amended BitString returned [1]

KEY IDEACount the 1s with a loop, use MOD 2 to see if the count is odd or even, then append the matching bit.
TOTAL 8 marks

Official mark scheme

Mark scheme for 9618/23/M/J/25 question 5
VIDEO
▶ Whole paper

Video solution of the whole paper · by Awab Aqib. 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.