ProgrammingHardInfosys · Cognizant

Prefix sums are computed for a = [4, 1, 7, 3, 2, 8] with P[0] = 0 and P[k] = a[1] + ... + a[k]. A range sum for 1-based positions l to r is P[r] - P[l-1]. What is printed for the range l = 2, r = 5?

Prefix sums are computed for a = [4, 1, 7, 3, 2, 8] with P[0] = 0 and P[k] = a[1] + ... + a[k]. A range sum for 1-based positions l to r is P[r] - P[l-1]. What is printed for the range l = 2, r = 5?
P[0] = 0
for k = 1 to 6: P[k] = P[k-1] + a[k]
Print P[5] - P[1]
  1. A. 12
  2. B. 11
  3. C. 13
  4. D. 21

Correct answer: C. 13

The sum from position 2 to position 5 is 1 + 7 + 3 + 2 = 13, which equals P[5] - P[1]. Subtracting P[2] drops one element, stopping at P[4] drops the last one, and reading P[6] adds an extra element.

More Pseudocode and Code Tracing questions

Exams that ask this topic