Question
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 _______.
Official answer and solution
- Official answer
- 55
- From
- Official GATE 2020 answer key
Solution
Trace the execution of static variables across recursive calls to fun1 and fun2.
Notice that fun1 and fun2 each declare their own distinct static variable named i, both initialized to 0 once at the start of execution:
- Let denote the static variable in
fun1. - Let denote the static variable in
fun2.
Behavior of fun1(k):
- When
fun1(k)is invoked with argument , if it increments by 1 and recursively callsfun1(k-1). - Thus, a call
fun1(k)executes the++istatement exactly times, increasing by , and returns the updated value of .
Trace of fun2(5) step by step:
- Initially: , .
- Step 1 ():
- Calls
fun1(5): increments by 5 , returns 5. - Updates : .
- Recursive call
fun2(4).
- Calls
- Step 2 ():
- Calls
fun1(4): increments by 4 , returns 9. - Updates : .
- Recursive call
fun2(3).
- Calls
- Step 3 ():
- Calls
fun1(3): increments by 3 , returns 12. - Updates : .
- Recursive call
fun2(2).
- Calls
- Step 4 ():
- Calls
fun1(2): increments by 2 , returns 14. - Updates : .
- Recursive call
fun2(1).
- Calls
- Step 5 ():
- Calls
fun1(1): increments by 1 , returns 15. - Updates : .
- Recursive call
fun2(0).
- Calls
- Step 6 ():
- Condition is false; returns .
All recursive returns pass back . Thus, fun2(5) returns 55.
Final answer
55
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2020 Computer Science and Information Technology (CS)
- Question
- 56 of 65, printed as CS Q.46
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.