Cambridge AS Level Computer Science 9618 · 11.3 Structured Programming

Q88 · 9618/21/O/N/24 Q4

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

Q889618/21/O/N/24original Q4Structured · 10 marks
Question 4 from 9618/21/O/N/24

Worked solution

(a)

Type: a run-time error [1]

Cause: dividing by zero, or trying to convert a string that is not numeric into a number [1]

(b)

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]

(c)

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
ENDFUNCTION

Function 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.

KEY IDEAValidate input before a calculation, and use a record to return more than one value from a function.
TOTAL 10 marks

Official mark scheme

Mark scheme for 9618/21/O/N/24 question 4
VIDEO
▶ 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.