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)
  1. A. 37
  2. B. 41
  3. C. 38
  4. 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.

More Pseudocode and Code Tracing questions

Exams that ask this topic