Question 1

OCR Computer Science June 2018 Paper 2AS18 marks

On the specification

(a)
1.4 Data types, data structures and algorithms
(b)(i)
2.2 Problem solving and programming
(b)(ii)
2.2 Problem solving and programming
(b)(iii)
1.4 Data types, data structures and algorithms2.2 Problem solving and programming
(b)(iv)
2.2 Problem solving and programming1.4 Data types, data structures and algorithms
Question text

1 A user enters whole numbers into a computer program. Each number entered is placed onto a stack. The stack is created using an array with a maximum of 20 elements. Part of the array, numStack, is shown when one number has been input. index stackItem 9 8 7 6 top 1 5 4 3 2 1 0 20 The pointer, top, points to the next free space in the stack. (a) Complete the diagram below to show the state of numStack after the user inputs the following numbers in the order given: 22 13 2 59 1000 index stackItem 9 8 7 6 top 5 4 3 2 1 0 20 [2] (b) A function, addItem, takes a number as a parameter and adds the number to the stack. The function returns true if this was successful, and false if the stack is already full. (i) Give one reason why a function is used instead of a procedure in this scenario. [1] (ii) The parameter can be passed by value or by reference. Describe what is meant by passing a parameter by value and by reference. By value By reference [4] (iii) The function addItem is written but is incomplete. Complete the function, addItem. function addItem (number) if top == then return false else numStack[ ] = top = + 1 endif endfunction [5] (iv) The procedure, calculate, takes each item in turn from the stack. It alternately adds then subtracts the numbers until there are none left. For example, if numStack contains: 2 6 5 12 It would perform 2 + 6 – 5 + 12 and output 15. 1 procedure calculate() 2 total = 0 3 add = true 4 if top == 0 then 5 print("Stack empty") 6 else 7 total = numStack[top - 1] 8 top = top – 1 9 while top != 0 10 if add == true then 11 total = total + numStack[top - 1] 12 add = false 13 else 14 total = total – numStack[top - 1] 15 add = true 16 endif 17 top = top - 1 18 endwhile 19 print(total) 20 endif 21 endprocedure Complete the trace table for the procedure calculate. The current array and pointer values when the procedure is called are on the first line of the trace table. numStack top 0 1 2 3 4 5 total add Output 5 20 2 6 12 8 [6]