9618/21/O/N/24 question 4: worked solution (October/November 2024, paper 21)

Show as plain text

Cambridge AS Level Computer Science 9618 · 11.3 Structured Programming Worked solution from the Programming Paper 2 Problem-solving and Programming booklet, Part 3 of 3. Q88 9618/21/O/N/24 original Q4 Structured · 10 marks 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 IDEA Validate input before a calculation, and use a record to return more than one value from a function. 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.