retagged by
274 views
2 votes
2 votes

What will be printed by the following program?

#include<stdio.h>
int func(int n, int * fg) {
    int t, f;
    if (n <= 1) {
        *fg = 1;
        return 1;
    }
    t = func(n - 1, fg);
    f = t + *fg;
    *fg = t;
    return f;
}
int main() {
    int x = 15;
    printf("%d\n", func(5, &x));
}
retagged by

1 Answer

0 votes
0 votes

Here variable x is sent into function “func” as pass by reference. The function “func” will be called 5 times. In the last function call, the value of ‘x’ will be made to 1 and 1 will be returned to the local variable ‘t’ of the 4th function call. Here the value of ‘t’ and ‘x’ will be added and stored in local variable f and returned to local variable ‘t’ of the 3rd function call, Again the process continues till the initial function call and 5 will be given to local variable ‘t’ of 1st function call. That ‘t’ and value of ‘x = 3’ (5 + 3 = 8)will be added and returned to main() function to print. 

(The function calls, return values and value of x are clearly drawn and shown in image please refer it)

Here totally 5 times the value of x will be changed.

Simply, 1 + 1 + 1 + 2 + 3 + 5 = 8 (w.r.t function calls)

Answer:

Related questions