Cambridge AS Level Computer Science 9618 · 11.3 Structured Programming

Q77 · 9618/21/M/J/23 Q4

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

Q779618/21/M/J/23original Q4Structured · 6 marks
Question 4 from 9618/21/M/J/23

Worked solution

Go through the string one character at a time. Copy each character to the new string, but swap it for the new character when it matches the original one.

FUNCTION Replace(OldString : STRING, Char1, Char2 : CHAR) RETURNS STRING
    DECLARE NewString : STRING
    DECLARE ThisChar : CHAR
    DECLARE Index : INTEGER
    NewString ← ""
    FOR Index ← 1 TO LENGTH(OldString)
        ThisChar ← MID(OldString, Index, 1)
        IF ThisChar = Char1 THEN
            ThisChar ← Char2
        ENDIF
        NewString ← NewString & ThisChar
    NEXT Index
    RETURN NewString
ENDFUNCTION

Function heading and ending including the parameters and return type [1]

Local variables declared, including the loop counter [1]

Loop for the length of OldString [1]

Each character extracted and tested against the original character inside the loop [1]

Characters joined with & to build NewString, replacing the character when needed, inside the loop [1]

NewString returned after the loop [1]

KEY IDEABuild a new string character by character with concatenation, swapping only the characters that match.
TOTAL 6 marks

Official mark scheme

Mark scheme for 9618/21/M/J/23 question 4
VIDEO
▶ Starts at Q4 (28:02)

Starts at Q4 (28:02) · by Pseudocode Pro. 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.