ProgrammingVery hardTCS NQT · Infosys · Capgemini

What will be the output of the following pseudocode? (Arrays are 0-indexed.)

What will be the output of the following pseudocode? (Arrays are 0-indexed.)
Integer a[6] = {4, 7, 1, 9, 3, 6}
Integer i = 0
For k = 1 to 5
    Integer j = (i + a[i]) mod 6
    Integer t = a[i]
    a[i] = a[j]
    a[j] = t
    i = j
End For
Print a[0], a[1], a[2], a[3], a[4], a[5]
  1. A. 3 1 9 3 7 6
  2. B. 3 7 4 9 1 6
  3. C. 4 7 1 9 3 6
  4. D. 1 7 4 9 3 6

Correct answer: D. 1 7 4 9 3 6

Each pass jumps from i to j = (i + a[i]) mod 6 using the value held at i before the swap, swaps the two cells, and continues from j. The walk visits indices 0, 4, 2, 0, 4 in turn, and the five swaps give the array shown.

More Pseudocode and Code Tracing questions

Exams that ask this topic