GATE | GATE-CS-2009 | Question 60
Output of following program?
#include <stdio.h> int fun( int n, int *f_p) { int t, f; if (n <= 1) { *f_p = 1; return 1; } t = fun(n- 1,f_p); f = t+ * f_p; *f_p = t; return f; } int main() { int x = 15; printf ( " %d \n" , fun(5, &x)); return 0; } |
(A) 6
(B) 8
(C) 14
(D) 15
Answer: (B)
Explanation:
Let x is stored at location 2468 i.e. &x = 2468 (dots are use just to ensure alignment) x = 15 fun(5, 2468) ...{t = fun(4, 2468) .......{t = fun(3, 2468) ...........{t = fun(2,2468) ...............{t = fun(1, 2468) ...................{// x=1 ........................return 1} ................t = 1 ................f = 2 //1+1 //since *f_p is x ................x = t = 1 ................return 2} ...........t = 2 ...........f = 2+1 ...........x = t = 2 ...........return 3} ........t = 3 ........f = 3+2 ........x = t = 3 ........return 5} ....t = 5 ....f = 5+3 ....x = t = 5 ....return 8} which implies fun (5,2468) is 8.