Worked solution from the Programming Paper 2 Problem-solving and Programming booklet, Part 1 of 3.
Find the operator by checking each character: the one that is not a digit. Split the string into the left value, the operator and the right value, then convert and calculate.
PROCEDURE Calculate(Expression : STRING)
DECLARE Val1, Val2, Index : INTEGER
DECLARE Result : REAL
DECLARE Par1, Par3 : STRING
DECLARE Par2, ThisChar : CHAR
FOR Index ← 1 TO LENGTH(Expression)
ThisChar ← MID(Expression, Index, 1)
IF IS_NUM(ThisChar) = FALSE THEN
Par1 ← LEFT(Expression, Index - 1)
Par2 ← ThisChar
Par3 ← RIGHT(Expression, LENGTH(Expression) - Index)
ENDIF
NEXT Index
Val1 ← STR_TO_NUM(Par1)
Val2 ← STR_TO_NUM(Par3)
CASE OF Par2
'+' : Result ← Val1 + Val2
'-' : Result ← Val1 - Val2
'*' : Result ← Val1 * Val2
'/' : Result ← Val1 / Val2
ENDCASE
OUTPUT Result
ENDPROCEDUREDeclare local variables for the three parts (and the loop counter) [1]
Loop through the characters of the string (until the operator is found), extracting one character each time [1]
Attempt to extract the three parts of the expression with string functions such as LEFT, MID and RIGHT [1]
All three parts extracted completely correctly [1]
Convert the two number strings to integers with STR_TO_NUM [1]
Attempt to deal with at least two of the operators + - * / (for example with CASE or IF) [1]
Correct calculation for all four operators and the result output [1]
Other correct methods score, for example a WHILE loop that stops at the operator.
Change PROCEDURE to FUNCTION and add the type of the value returned. Write:
FUNCTION Calculate(Expression : STRING) RETURNS REAL
FUNCTION with the parameter and RETURNS REAL (a number type) [1]
Choose a correctly formatted string that divides by zero.
Example string: "23/0" (any division by zero scores) [1]
Explanation: dividing by zero gives no valid result (it is undefined or infinity), so the program cannot calculate it and may crash [1]
▶ Whole paper
Video solution of the whole paper · 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.