Worked solution from the Programming Paper 2 Problem-solving and Programming booklet, Part 3 of 3.
Count one match at a time. Compare each character with the parameter, so the check is case sensitive.
FUNCTION GetNum(ThisString : STRING, ThisChar : CHAR) RETURNS INTEGER
DECLARE Index, Count : INTEGER
Count ← 0
FOR Index ← 1 TO LENGTH(ThisString)
IF MID(ThisString, Index, 1) = ThisChar THEN
Count ← Count + 1
ENDIF
NEXT Index
RETURN Count
ENDFUNCTIONFunction heading and ending including the parameters and return type [1]
Local INTEGER variables declared for Index and Count [1]
Loop for the length of ThisString [1]
Character extracted and compared with the parameter inside the loop [1]
Count incremented when they match [1]
Count returned after the loop [1]
▶ Starts at Q4 (27:45)
Starts at Q4 (27:45) · 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.