Cambridge AS Level Computer Science 9618 · 11.1 Programming Basics

Q8 · 9618/21/O/N/22 Q7

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

Q89618/21/O/N/22original Q7Structured · 10 marks
Question 7 from 9618/21/O/N/22

Worked solution

(a)(i)

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
ENDPROCEDURE

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

(a)(ii)

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]

(b)

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]

KEY IDEASplit the string at the first non-digit character, convert the two parts to numbers and pick the calculation from the operator.
TOTAL 10 marks

Official mark scheme

Mark scheme for 9618/21/O/N/22 question 7
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.