ProgrammingHardProduct company OA · 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 a[5] = {1, 2, 3, 4, 5}, t
for (i = 0 to 4)
    t = a[i]
    a[i] = a[4 - i]
    a[4 - i] = t
end for
Print a[0], a[1], a[2], a[3], a[4]
  1. A. 5 4 3 2 1
  2. B. 1 2 3 4 5
  3. C. 5 2 3 4 1
  4. D. 1 4 3 2 5

Correct answer: B. 1 2 3 4 5

The loop runs over the WHOLE array instead of stopping at the middle. i = 0, 1 reverse the array (5 4 3 2 1), i = 2 swaps the middle with itself, and i = 3, 4 swap the same pairs back. The array ends unchanged. The correct reversal loop runs i from 0 to n/2 − 1.

More Pseudocode and Code Tracing questions

Exams that ask this topic