ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode? (Arrays are indexed from 0; / is integer division; 'from … to …' includes both ends.)

What will be the output of the following pseudocode? (Arrays are indexed from 0; / is integer division; 'from … to …' includes both ends.)
Integer a[6] = {1, 2, 3, 4, 5, 6}, n = 6, t
for (each i from 0 to n / 2)
    t = a[i]
    a[i] = a[n - 1 - i]
    a[n - 1 - i] = t
end for
Print a[0], a[2], a[3], a[5]
  1. A. 6 3 4 1
  2. B. 6 4 3 1
  3. C. 1 3 4 6
  4. D. 6 3 4 2

Correct answer: A. 6 3 4 1

The loop runs for i = 0, 1, 2, 3 — one iteration too many for a reversal. After i = 0, 1, 2 the array is reversed: 6 5 4 3 2 1. The extra iteration i = 3 swaps a[3] with a[n − 1 − 3] = a[2], undoing the middle swap: 6 5 3 4 2 1. So the output is 6 3 4 1. '6 4 3 1' is what a correct reversal (i up to n/2 − 1) would print.

More Pseudocode and Code Tracing questions

Exams that ask this topic