9618/21/M/J/23 question 4: worked solution (May/June 2023, paper 21)

Show as 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. Q77 9618/21/M/J/23 original Q4 Structured · 6 marks 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 IDEA Build a new string character by character with concatenation, swapping only the characters that match. TOTAL 6 marks Official mark scheme VIDEO ▶ Starts at Q4 (28:02) Starts at Q4 (28:02) · by Pseudocode Pro. Tap the picture to open it on YouTube.