9618/21/O/N/22 question 7: worked solution (October/November 2022, paper 21)
Show as plain textHide plain text
Cambridge AS Level Computer Science 9618 · 11.1 Programming Basics Worked solution from the Programming Paper 2 Problem-solving and Programming booklet, Part 1 of 3. Q8 9618/21/O/N/22 original Q7 Structured · 10 marks 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 IDEA Split 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 VIDEO ▶ Whole paper Video solution of the whole paper · by Pseudocode Pro. Tap the picture to open it on YouTube.