ProgrammingModerateTCS NQT · Accenture pattern

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[] = {5, 3, 8, 1, 9, 2}
Integer m1 = -1, m2 = -1
for (each x in a)
    if (x > m1)
        m2 = m1
        m1 = x
    else if (x > m2)
        m2 = x
    end if
end for
Print m1, m2
  1. A. 9 8
  2. B. 9 5
  3. C. 8 9
  4. D. 9 9

Correct answer: A. 9 8

One pass tracks the largest and second largest: 5 → (5, −1), 3 → (5, 3), 8 → (8, 5), 1 → no change, 9 → (9, 8), 2 → no change. Forgetting to shift m1 into m2 would leave m2 = 5.

More Pseudocode and Code Tracing questions

Exams that ask this topic