ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode? (Arrays are indexed from 0.)

What will be the output of the following pseudocode? (Arrays are indexed from 0.)
Integer arr[5] = {3, 1, 4, 1, 5}
for (each i from 1 to 4)
    arr[i] = arr[i] + arr[i - 1]
end for
Print arr[4] - arr[1]
  1. A. 9
  2. B. 11
  3. C. 4
  4. D. 10

Correct answer: D. 10

The loop turns the array into running (prefix) sums {3, 4, 8, 9, 14}. arr[4] - arr[1] = 14 - 4 = 10, which is the sum of the original elements at indices 2 to 4 (4 + 1 + 5). Using the original values gives 5 - 1 = 4.

More Pseudocode and Code Tracing questions

Exams that ask this topic