ProgrammingHardCapgemini · Infosys 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[4] = {2, 3, 1, 0}
for (each i from 0 to 3)
    arr[i] = arr[arr[i]]
end for
Print arr[0], arr[1], arr[2], arr[3]
  1. A. 1 0 1 0
  2. B. 1 0 3 2
  3. C. 0 1 1 0
  4. D. 1 0 0 1

Correct answer: D. 1 0 0 1

The array changes in place, so later steps read values already overwritten. i = 0: arr[0] = arr[2] = 1. i = 1: arr[1] = arr[3] = 0. i = 2: arr[2] = arr[1] = 0 (already changed). i = 3: arr[3] = arr[0] = 1. Using the original array gives the trap 1 0 3 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic