9618/22/M/J/22 question 6: worked solution (May/June 2022, paper 22)

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. Q70 9618/22/M/J/22 original Q6 Structured · 7 marks 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 IDEA Build 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 VIDEO ▶ Whole paper Video solution of the whole paper · by Awab Aqib. Tap the picture to open it on YouTube.