ProgrammingHardCapgemini · Infosys pattern

What will be the output of the following pseudocode (reversing an array in groups of size k)? (Arrays are indexed from 0.)

What will be the output of the following pseudocode (reversing an array in groups of size k)? (Arrays are indexed from 0.)
Integer arr[8] = {1, 2, 3, 4, 5, 6, 7, 8}
Integer k = 3
Integer n = 8
for (each i from 0 to n - 1 step k)
    Integer l = i, r = min(i + k, n) - 1
    while (l < r)
        swap(arr[l], arr[r])
        l = l + 1
        r = r - 1
    end while
end for
Print arr
  1. A. [3, 2, 1, 6, 5, 4, 8, 7]
  2. B. [8, 7, 6, 5, 4, 3, 2, 1]
  3. C. [1, 2, 3, 4, 5, 6, 7, 8]
  4. D. [3, 2, 1, 6, 5, 4, 7, 8]

Correct answer: A. [3, 2, 1, 6, 5, 4, 8, 7]

Each group of 3 consecutive elements is reversed independently: {1,2,3}->{3,2,1}, {4,5,6}->{6,5,4}, and the final partial group {7,8} (only 2 elements) reverses to {8,7}, giving [3,2,1,6,5,4,8,7].

More Pseudocode and Code Tracing questions

Exams that ask this topic