ProgrammingModerateInfosys · Capgemini pattern
What will be the output of the following pseudocode?
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 division
End Function
Print f(20)- A. 37
- B. 41
- C. 38
- D. No output: the recursion never ends
Correct answer: C. 38
f(20) = 20 + f(10) = 20 + 10 + f(5) = 20 + 10 + 5 + f(2) = 20 + 10 + 5 + 2 + f(1) = 38, since 5 / 2 = 2 and f(1) = 1. Rounding 5 / 2 up to 3 gives 41, treating the base case as 0 gives 37, and integer division always reaches 1, so the recursion does end.
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 count = 0 for (i = 2 to 30) Boolean prime = true for (d = 2 while d d <= i)…
- What will be the output of the following pseudocode? Integer a[6] = {1, 2, 3, 4, 5, 6}, n = 6 for (i = 0 to n/2 - 1) swap(a[i], a[n - 1…
- What will be the output of the following pseudocode? // C-style integer arithmetic: / truncates toward zero, mod keeps the dividend's sign…
- What will be the output of the following pseudocode? Integer Function g(Integer n) if (n <= 1) return n return g(n - 1) + 2 g(n - 2) End…
- What will be the output of the following pseudocode? String s = "" Integer n = 13 while (n > 0) s = (n mod 2) + s // prepend the digit n =…
- What will be the output of the following pseudocode? Integer i = 1, j, c = 0 while (i <= 16) j = i while (j <= 16) c = c + 1 j = j 2 end…