ExamBank Scot · Higher Computing Science question bank · All Higher Computing Science questions
6 marks · Pre-defined functions
Using a programming language of your choice, write the code for line 10. The function checkHarshad is used to assign a value to the variable finalResult. Using a programming language of your choice, write the missing code at Line 41 to call the function. The program makes use of local variables. Explain why the scope of the variable total is local. Explain why the use of local variables makes programs more efficient. A Harshad number is an integer that is exactly divisible by the sum of its digits. For example: 132 is a Harshad number. The digits of 132 are 1, 3 and 2 and the sum of these digits is 6. 132 is exactly divisible by 6 (132 ÷ 6 = 22). 251 is not a Harshad number. The digits of 251 are 2, 5 and 1 and the sum of these digits is 8. 251 is not exactly divisible by 8 (251 ÷ 8 = 31.375). The algorithm below is used to check if a number is a Harshad number or not. Line 1 FUNCTION checkHarshad(INTEGER number) RETURNS INTEGER Line 2 DECLARE numberString AS STRING INITIALLY "" Line 3 SET numberString TO <parameter number converted to a string of digits> Line 4 DECLARE total AS INTEGER INITIALLY 0 Line 5 FOR index FROM 0 TO length(numberString) DO Line 6 SET digitChar TO numberString[index] Line 7 SET digit TO <digitChar converted to an integer> Line 8 SET total TO total + digit Line 9 END FOR Line 10 <Divide number by total and store the remainder in the variable named result> Line 11 RETURN result Line 12 END FUNCTION ... Line 40 RECEIVE checkNo FROM INTEGER KEYBOARD Line 41 Line 42 IF finalResult = 0 THEN Line 43 SEND checkNo & "is a Harshad number" TO DISPLAY Line 44 ELSE Line 45 SEND checkNo & "is not a Harshad number" TO DISPLAY Line 46 END IF
• use of mod function/operator • arguments (number, total) in order and assignment to result Example answer: SET result TO number MOD total • use of function name checkHarshad with assignment to finalResult • parameter checkNo passed into function finalResult = checkHarshad(checkNo) It is declared/used/accessible inside the function/lines 1 – 12. The variables are only in memory when the function is being executed.