ProgrammingHardInfosys · Capgemini pattern
What will be the output of the following pseudocode?
What will be the output of the following pseudocode?
Integer a[] = {5, 1, 4, 2, 3}, c = 0
for (i = 0 to 4)
for (j = i + 1 to 4)
if (a[i] > a[j]) c = c + 1
end for
end for
Print c- A. 4
- B. 10
- C. 5
- D. 6
Correct answer: D. 6
c counts inversions: 5 is greater than the 4 values after it; 4 > 2 and 4 > 3; 1, 2, 3 add nothing → 6. This equals the number of swaps bubble sort would make. O(n²); merge sort counts them in O(n log n).
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? String s = "PROGRAM", r = "" for (i = length(s) - 1 down to 0 step 2) r = r + s[i]…
- What will be the output of the following pseudocode? Integer n = 5, t = 0 for (i = 1 to n) if (i mod 2 == 1) t = t + i i else t = t - i…
- What will be the output of the following pseudocode? Integer a = 1, b = 1, t for (k = 1 to 5) t = a + b a = b b = t if (b mod 2 == 0)…
- What will be the output of the following pseudocode? Integer Function f(Integer n, Integer acc) if (n == 0) return acc return f(n - 1…
- What will be the output of the following pseudocode? Integer x = 100, c = 0 while (x > 1) if (x mod 2 == 0) x = x / 2 else x = 3 x + 1 c =…
- What will be the output of the following pseudocode? Integer a[] = {1, 3, 5, 7, 9, 11, 13} Integer lo = 0, hi = 6, t = 11, steps = 0, mid…