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 _________.
GATE 2020 · Programming and Data Structures · Recursion · medium
Answer: fun2(5) returns 55.
Determine execution order of fun1 calls: fun2(5) calls fun1(5) first, then recurses to fun2(4) which calls fun1(4), then fun2(3) calls fun1(3), then fun2(2) calls fun1(2), then fun2(1) calls fun1(1). So fun1 is called with arguments 5, 4, 3, 2, 1 in that order.
Track fun1's static i and return values across all calls: fun1(5): i goes 0->5, returns 5. fun1(4): i continues 5->9, returns 9. fun1(3): i continues 9->12, returns 12. fun1(2): i continues 12->14, returns 14. fun1(1): i continues 14->15, returns 15.
Sum fun1 return values to get fun2's return value: fun2's static i = 0 + 5 = 5; then 5 + 9 = 14; then 14 + 12 = 26; then 26 + 14 = 40; then 40 + 15 = 55. fun2(5) returns 55.