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- A. 9 8
- B. 9 5
- C. 8 9
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? Integer Function fun(Integer a, Integer b) if (b == 0) return 1 if (b mod 2 == 0)…
- What will be the output of the following pseudocode? Integer n = 45, c = 0 while (n != 0) c = c + (n & 1) n = n >> 1 end while Print c
- What will be the output of the following pseudocode? Integer x = 10, s = 0 while (x > 0) s = s + x x = x - 3 end while Print s, x
- What will be the output of the following pseudocode? Integer a = 10, b = 20, c = 30, r if (a > b AND b > c) r = 1 else if (a < b OR c < b)…
- What will be the output of the following pseudocode? Integer Function f(Integer n) if (n == 1) return 1 return f(n / 2) + n // integer…
- What will be the output of the following pseudocode? Integer count = 0 for (i = 2 to 30) Boolean prime = true for (d = 2 while d d <= i)…