ProgrammingModerateTCS NQT · Accenture

The procedure below finds the smallest 0-based index i at which the prefix sum of [4, -1, 3, -2, 5] reaches at least 7. It prints i. What is printed?

The procedure below finds the smallest 0-based index i at which the prefix sum of [4, -1, 3, -2, 5] reaches at least 7. It prints i. What is printed?
s = 0
for i = 0 to n - 1
    s = s + a[i]
    if s >= 7 then print i; stop
end for
  1. A. 2
  2. B. 5
  3. C. 4
  4. D. 3

Correct answer: C. 4

Prefix sums are 4, 3, 6, 4 and 9, so the first index reaching 7 is index 4 (value 9). Using a threshold of 6 stops at index 2, the 1-based index is 5, and the index of the minimum element is 3.

More Pseudocode and Code Tracing questions

Exams that ask this topic