ProgrammingModerateTCS NQT · Accenture pattern

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[5] = {2, 4, 6, 8, 10}
for (i = 1 to 4)
    a[i] = a[i] + a[i - 1]
end for
Print a
  1. A. 2 6 10 14 18
  2. B. 2 4 6 8 10
  3. C. 2 6 12 20 28
  4. D. 2 6 12 20 30

Correct answer: D. 2 6 12 20 30

Each a[i − 1] has already been updated, so the loop builds running (prefix) sums: 2, 2+4, 6+6, 12+8, 20+10. Using the original neighbour each time would give 2, 6, 10, 14, 18.

More Pseudocode and Code Tracing questions

Exams that ask this topic