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- A. 3
- B. 7
- C. 15
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The procedure below uses exponentiation by squaring on the exponent 37. It counts one multiplication into result each time the current…
- Recursive merge sort splits an array of length n into halves of length n div 2 and n minus n div 2, and calls itself on each half unless…
- The loop below multiplies i by 3 each time while i is less than 1000, starting from i = 1, and counts the iterations. What is printed? i =…
- A nested loop counts the pairs (i, j) with 1 <= j <= i <= 6 that also satisfy i + j even. The procedure prints the count. What is printed?…
- The procedure below counts the numbers i from 1 to 100 whose binary form has exactly three 1 bits (bits are counted by repeatedly taking n…
- A string of parentheses "(()())((" is scanned by the procedure below. The variable open counts unmatched '(' at the end, and the procedure…