ProgrammingHardGoldman Sachs OA · Amazon OA
What will be the output of the following pseudocode?
What will be the output of the following pseudocode?
Integer a[9] = {3, 3, 4, 2, 4, 4, 2, 4, 2}
Integer cand = 0, cnt = 0
for (each i from 0 to 8)
if (cnt == 0)
cand = a[i]
cnt = 1
else if (a[i] == cand)
cnt = cnt + 1
else
cnt = cnt - 1
end if
end for
Print cand, cnt- A. 4 1
- B. 4 4
- C. 3 1
- D. 4 0
Correct answer: A. 4 1
Boyer–Moore voting: 3 gets 2 votes, cancelled by 4 and 2; then 4 rises to 2, falls to 1 at the next 2, rises to 2 at the next 4, and the last 2 cancels down to 1. Output 4 1 (4 is the true majority here: 4 of 9).
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 a[7] = {16, 17, 4, 3, 5, 2, 1} Integer mx = a[6], c = 1 for (each i from 5…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer nxt[6] = {3, 5, 0, 1, 2, 4} Integer x = 0, steps…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer a[6] = {4, 5, 2, 25, 7, 8}, res[6] Stack st =…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer h[12] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}…
- What will be the output of the following pseudocode? (code(c) gives a letter's character code) String s = "PROGRAMMING", r = "" Boolean…
- What will be the output of the following pseudocode? String s = " the quick brown fox " Integer words = 0 Boolean inWord = false for (each…