Worked solution from the Programming Paper 2 Problem-solving and Programming booklet, Part 3 of 3.
Type: a run-time error [1]
Cause: dividing by zero, or trying to convert a string that is not numeric into a number [1]
Give one reason and one thing avoided:
Reason: the check and calculation do one specific task, so a change is made in one place only. Other accepted reasons: a library routine already exists, or the program is simpler to understand, design, test and maintain [1]
Avoided: repeated (duplicated) code, or errors caused by different copies of the check and calculation [1]
Check both strings with IS_NUM, convert them, check the divisor is not zero, then fill in the record:
FUNCTION Evaluate(NumStr1, NumStr2 : STRING) RETURNS Result
DECLARE RetVal : Result
DECLARE Num1, Num2 : REAL
RetVal.Done ← FALSE
IF IS_NUM(NumStr1) = TRUE AND IS_NUM(NumStr2) = TRUE THEN
Num1 ← STR_TO_NUM(NumStr1)
Num2 ← STR_TO_NUM(NumStr2)
IF Num2 <> 0 THEN
RetVal.Value ← Num1 / Num2
RetVal.Done ← TRUE
ENDIF
ENDIF
RETURN RetVal
ENDFUNCTIONFunction heading, two parameters and ending [1]
Return type Result [1]
Local variable of type Result declared [1]
IS_NUM() used on both strings [1]
STR_TO_NUM() used on both strings [1]
Divisor checked as not zero, then the calculation stored in Value, Done set to TRUE, and the Result variable returned with both fields set [1]
Only six marks are available from these points.
▶ 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.