ProgrammingVery hardAmazon OA · Infosys SP

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[5] = {7, 7, 5, 7, 6}
Integer m1 = -1, m2 = -1
for (each i from 0 to 4)
    if (a[i] >= m1)
        m2 = m1
        m1 = a[i]
    else if (a[i] > m2)
        m2 = a[i]
    end if
end for
Print m1, m2
  1. A. 7 6
  2. B. 7 7
  3. C. 7 5
  4. D. 7 -1

Correct answer: B. 7 7

Because of >=, the repeated 7 pushes the old 7 down into m2: after a[1], m1 = m2 = 7, and nothing smaller can replace it. Output 7 7. With a strict > (and skipping equal values) the second largest distinct value 6 would be found.

More Pseudocode and Code Tracing questions

Exams that ask this topic