Practice Questions for Recursion | Set 7
Question 1 Predict the output of the following program. What does the following fun() do in general?
#include <stdio.h> int fun ( int n, int *fp ) { int t, f; if ( n <= 1 ) { *fp = 1; return 1; } t = fun ( n-1, fp ); f = t + *fp; *fp = t; return f; } int main() { int x = 15; printf("%d\n",fun(5, &x;)); return 0; } |
chevron_right
filter_none
Output:
8
The program calculates nth Fibonacci Number. The statement t = fun ( n-1, fp ) gives the (n-1)th Fibonacci number and *fp is used to store the (n-2)th Fibonacci Number. Initial value of *fp (which is 15 in the above program) doesn’t matter. Following recursion tree shows all steps from 1 to 10, for execution of fun(5, &x).
(1) fun(5, fp)
/ \
(2) fun(4, fp) (10) t = 5, f = 8, *fp = 5
/ \
(3) fun(3, fp) (9) t = 3, f = 5, *fp = 3
/ \
(4) fun(2, fp) (8) t = 2, f = 3, *fp = 2
/ \
(5) fun(1, fp) (7) t = 1, f = 2, *fp = 1
/
(6) *fp = 1
Question 2: Predict the output of the following program.
#include <stdio.h> void fun(int n) { if(n > 0) { fun(n-1); printf("%d ", n); fun(n-1); } } int main() { fun(4); return 0; } |
chevron_right
filter_none
Output
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
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.
Recommended Posts:
- Practice Questions for Recursion | Set 3
- Practice Questions for Recursion | Set 6
- Practice Questions for Recursion | Set 5
- 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
Improved By : Akanksha_Rai



