Worked solution from the Programming Paper 2 Problem-solving and Programming booklet, Part 3 of 3.
Go through the string one character at a time. Build up each number as text. At a comma, convert it, add it to the total and start again. Deal with the last number after the loop, because it has no comma after it.
PROCEDURE Parse(InString : STRING)
DECLARE Count, Total, Index : INTEGER
DECLARE Average : REAL
DECLARE NumString : STRING
DECLARE ThisChar : CHAR
CONSTANT COMMA = ','
Count ← 0
Total ← 0
NumString ← ""
FOR Index ← 1 TO LENGTH(InString)
ThisChar ← MID(InString, Index, 1)
IF ThisChar = COMMA THEN
Total ← Total + STR_TO_NUM(NumString)
Count ← Count + 1
NumString ← ""
ELSE
NumString ← NumString & ThisChar
ENDIF
NEXT Index
Total ← Total + STR_TO_NUM(NumString)
Count ← Count + 1
Average ← Total / Count
OUTPUT "The total was ", Total, " and the average was ", Average
ENDPROCEDUREDeclare and set Count, Total and NumString to start values [1]
A loop over the characters of InString [1]
Extract a character and test for a comma inside the loop [1]
If a comma, convert NumString to a number and update Total and Count [1]
...and reset NumString to empty [1]
Otherwise add the character to NumString [1]
Work out the average and output the total and average after the loop (including the last number) [1]
▶ 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.