Practice Questions for Recursion | Set 5
Question 1
Predict the output of following program. What does the following fun() do in general?
#include<stdio.h> int fun(int a, int b) { if (b == 0) return 0; if (b % 2 == 0) return fun(a+a, b/2); return fun(a+a, b/2) + a; } int main() { printf("%d", fun(4, 3)); getchar(); return 0; } |
chevron_right
filter_none
Output: 12
It calulates a*b (a multipied 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.
#include<stdio.h> int fun(int a, int b) { if (b == 0) return 1; if (b % 2 == 0) return fun(a*a, b/2); return fun(a*a, b/2)*a; } int main() { printf("%d", fun(4, 3)); getchar(); return 0; } |
chevron_right
filter_none
Output: 64
It calulates a^b (a raised to power b).
Question 3
Predict the output of following program. What does the following fun() do in general?
#include<stdio.h> int fun(int n) { if (n > 100) return n - 10; return fun(fun(n+11)); } int main() { printf(" %d ", fun(99)); getchar(); return 0; } |
chevron_right
filter_none
Output: 91
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
Returned value of fun() is 91 for all integer rguments n <= 101, and n - 10 for n > 101. This function is known as McCarthy 91 function.
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.
Recommended Posts:
- Practice Questions for Recursion | Set 3
- Practice Questions for Recursion | Set 7
- Practice Questions for Recursion | Set 6
- Practice Questions for Recursion | Set 4
- Practice Questions for Recursion | Set 2
- Practice Questions for Recursion | Set 1
- Practice questions for Linked List and Recursion
- Recursive Practice Problems with Solutions
- Recursion
- Tail Recursion
- Sum of the series 1^1 + 2^2 + 3^3 + ..... + n^n using recursion
- Find the value of ln(N!) using Recursion
- Sort a stack using recursion
- Generating all possible Subsequences using Recursion
- Generating subarrays using recursion



