ITPEC IP October 2025 Question 8
In the program below, the function subTotal receives an integer array inputarr as an argument, returns an array arr in which the sum of all elements of original array inputarr up to that location is stored in the same location. Which of the following is the correct combination of pieces of code to be inserted into A and B in the program. Here, the size of the array inputarr is greater than 1, and elements outside the bounds of the array must not be accessed, and the array index starts at 1.
Explanation
A: 2, B: arr[i − 1] — arr[1] is set before the loop, so the loop starts at 2 and adds each input to the running sum stored just before it.
The sum up to position i is the sum up to i − 1 plus the element at i: arr[i] ← inputarr[i] + arr[. For inputarr = {3, 1, 4, 2}:
- •
arr[1]= 3 (before the loop) - •i = 2: 1 + 3 = 4
- •i = 3: 4 + 4 = 8
- •i = 4: 2 + 8 = 10
The result {3, 4, 8, 10} holds every running total, and no index outside 1 to n is touched.
Answer (d)
Why not others:
- •(a) — starting at 1 recomputes
arr[1], andarr[is still 0 when read; at i = n it readsi + 1] arr[, outside the arrayn + 1] - •(b) — at i = 1 it reads
arr[0], which does not exist in an array whose index starts at 1 - •(c) —
arr[has not been computed yet (it is still 0), so each element just copies the input, and at i = n it reads outside the arrayi + 1]
Key rule: A running (prefix) sum builds each element from the one before it, arr[i] = arr[, so the first element is set on its own and the loop starts at the second.
Algorithm and Programming · AI-written, may contain errors
This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official IP past-paper collection or Report an issue.