ProgrammingVery hardAmazon OA · Infosys SP

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[8] = {1, 1, 2, 2, 2, 3, 5, 5}
Integer k = 1
for (each i from 1 to 7)
    if (a[i] != a[k - 1])
        a[k] = a[i]
        k = k + 1
    end if
end for
Print k, a[k - 1], a[k]
  1. A. 4 5 5
  2. B. 4 3 5
  3. C. 4 5 2
  4. D. 8 5 5

Correct answer: C. 4 5 2

The loop compacts the distinct values to the front: {1, 2, 3, 5, …}, so k = 4 and a[3] = 5. The rest of the array is untouched old data; a[4] still holds the original 2. Output 4 5 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic