ProgrammingHardTCS NQT · Accenture

A recursive function is written as below. The procedure counts the calls made for input 7, including the first call. What is printed?

A recursive function is written as below. The procedure counts the calls made for input 7, including the first call. What is printed?
function f(n)
    if n <= 1 then return
    f(n div 2); f(n div 2)
end function
count = number of calls made by f(7), including the first call
Print count
  1. A. 3
  2. B. 7
  3. C. 15
  4. D. 4

Correct answer: B. 7

The calls are f(7) once, f(3) twice, and f(1) four times, which is 7 in total. Making only one recursive call gives 3, using the base case n <= 0 adds the calls on 0 and gives 15, and counting only the leaf calls gives 4.

More Pseudocode and Code Tracing questions

Exams that ask this topic