ProgrammingHardInfosys · Capgemini pattern

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer c = 0
Procedure rec(Integer k)
    c = c + 1
    if (k <= 1) return
    rec(k / 2)
    rec(k / 2)
End Procedure
rec(6)
Print c
  1. A. 5
  2. B. 7
  3. C. 9
  4. D. 15

Correct answer: B. 7

rec(6) calls rec(3) twice; each rec(3) calls rec(1) twice. Calls: 1 + 2·(1 + 2) = 7. The recursion tree is binary with depth ⌊log₂ k⌋, so roughly 2k calls – T(k) = 2T(k/2) + 1 = O(k).

More Pseudocode and Code Tracing questions

Exams that ask this topic