ProgrammingVery hardTCS NQT · Infosys

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[5] = {2, 5, 9, 14, 20}, i
for (i = 1; i < 5; i = i + 1)
    a[i] = a[i] - a[i - 1]
end for
for (i = 4; i >= 1; i = i - 1)
    a[i] = a[i] + a[i - 1]
end for
Print a[0], a[1], a[2], a[3], a[4]
  1. A. 2 3 6 8 12
  2. B. 2 5 9 14 20
  3. C. 2 3 3 5 6
  4. D. 2 5 9 14 201

Correct answer: B. 2 5 9 14 20

The first loop uses already-updated left neighbours and gives 2, 3, 6, 8, 12. The second loop (running right to left) undoes it: 12 + 8 = 20, 8 + 6 = 14, 6 + 3 = 9, 3 + 2 = 5, restoring the original array.

More Pseudocode and Code Tracing questions

Exams that ask this topic