GATE 2020 CS – Question 56
Consider the following C functions.
int fun1(int n) {
static int i = 0;
if (n > 0) {
++i;
fun1(n-1);
}
return(i);
}
int fun2(int n) {
static int i = 0;
if (n > 0) {
i = i + fun1(n);
fun2(n-1);
}
return(i);
}The return value of fun2(5) is ______.
Practise this question in The GATE Grind →
Show answer and explanation
Correct answer: 55 to 55
Explanation
`fun1` has a `static int i`, so it keeps growing across calls: each call to `fun1(n)` recurses `n` times (increasing `i` once per level) and returns the current `i`.
`fun2(5)` calls `fun1(n)` for $n=5,4,3,2,1$ in turn and accumulates the results in its **own** static `i`.
- `fun1(5)`: `i` becomes 5, returns 5. `fun2`'s $i=5$.
- `fun1(4)`: `i` becomes 9, returns 9. `fun2`'s $i=5+9=14$.
- `fun1(3)`: `i` becomes 12, returns 12. `fun2`'s $i=26$.
- `fun1(2)`: `i` becomes 14, returns 14. `fun2`'s $i=40$.
- `fun1(1)`: `i` becomes 15, returns 15. `fun2`'s $i=55$.
`fun2(5)` returns its static `i`, which is **55**.