VOOZH about

URL: https://www.geeksforgeeks.org/dsa/practice-questions-for-recursion-set-5/

⇱ Practice Recursion - Hard - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Practice Recursion - Hard

Last Updated : 10 Apr, 2026

Question 1: Predict the output of the following program. What does the following fun() do in general?  

It calculates a*b (a multiplied b).

Question 2 : In question 1, if we replace + with * and replace return 0 with return 1, then what does the changed function do? Following is the changed function. 

It calculates a^b (a raised to power b).

Question 3 : Predict the output of the following program. What does the following fun() do in general?  

fun(99) = fun(fun(110)) since 99 ? 100
= fun(100) since 110 > 100
= fun(fun(111)) since 100 ? 100
= fun(101) since 111 > 100
= 91 since 101 > 100

Answer: The returned value of fun() is 91 for all integer arguments n 101. This function is known as McCarthy 91 function.

Question 4 : Consider the following recursive function. Let len be the length of the string s and num be the number of characters printed on the screen. Give the relation between num and len where len is always greater than 0. 

Answer: The following relathionsip between num and len: num = 2^len - 1

s[0] is 1 time printed
s[1] is 2 times printed
s[2] is 4 times printed
s[i] is printed 2^i times
s[strlen(s)-1] is printed 2^(strlen(s)-1) times
total = 1+2+....+2^(strlen(s)-1)
= (2^strlen(s)) - 1

Question 5 : Guess the output of the following code.

Answer: The main() function calls fun(1). fun(1) prints 1 and calls fun(fun(fun(2))). Then fun(2) prints 2 and calls fun(fun(fun(3))). At fun(3), the condition count < 3 becomes false, so it only prints 3 and returns 3. Now all the nested calls start resolving. Each remaining call becomes fun(3), which again prints 3 and returns 3. This process repeats as the nested calls unwind one by one. As a result, 3 gets printed multiple times (5 times in total). 

Question 6 : Predict the output of the following program. 


 fun(4)
/
fun(3), print(4), fun(3) [fun(3) prints 1 2 1 3 1 2 1]
/
fun(2), print(3), fun(2) [fun(2) prints 1 2 1]
/
fun(1), print(2), fun(1) [fun(1) prints 1]
/
fun(0), print(1), fun(0) [fun(0) does nothing]

Please write comments if you find any of the answers/codes incorrect, or you want to share more information/questions about the topics discussed above.

Comment
Article Tags:
Article Tags: