ProgrammingHardAccenture · Cognizant 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] = {2, 4, 6, 8, 10}
Integer prefix[6]
prefix[0] = 0
for (each i from 0 to 4)
    prefix[i + 1] = prefix[i] + arr[i]
end for
Print prefix[4] - prefix[1]
  1. A. 20
  2. B. 16
  3. C. 18
  4. D. 24

Correct answer: C. 18

prefix builds running totals: {0,2,6,12,20,30}. prefix[4]-prefix[1] gives the sum of arr[1..3] (indices 1,2,3): 4+6+8 = 18.

More Pseudocode and Code Tracing questions

Exams that ask this topic