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 is _________
View worked solution
Answer: 55
To find the return value of fun2(5), we trace the execution step-by-step. Both functions use static variables, which retain their values across multiple function calls.
- Let be the static variable inside
fun1(initially ). Callingfun1(k)increments by and returns the updated value of . - Let be the static variable inside
fun2(initially ).
Tracing the recursive calls of fun2(5):
fun2(5): Callsfun1(5). becomes .fun1(5)returns . .fun2(4): Callsfun1(4). becomes .fun1(4)returns . .fun2(3): Callsfun1(3). becomes .fun1(3)returns . .fun2(2): Callsfun1(2). becomes .fun1(2)returns . .fun2(1): Callsfun1(1). becomes .fun1(1)returns . .fun2(0): Base case (). Returns .
Thus, the final return value of fun2(5) is 55.
Free practice · Your answers on this page are not saved.
