Cambridge AS Level Computer Science 9618 · 11.3 Structured Programming

Q70 · 9618/22/M/J/22 Q6

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

Q709618/22/M/J/22original Q6Structured · 7 marks
Question 6 from 9618/22/M/J/22

Worked solution

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
ENDPROCEDURE

Declare 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]

KEY IDEABuild each number character by character, process it at each comma, and remember to process the final number after the loop.
TOTAL 7 marks

Official mark scheme

Mark scheme for 9618/22/M/J/22 question 6
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.