Consider the following C function:
int f(int n)
{
static int i = 1;
if(n >= 5) return n;
n = n+i;
i++;
return f(n);
}
The value returned by is:
View worked solution
Answer: C
To find the value returned by the call f(1), we trace the execution step-by-step. Note that the variable i is declared as static, which means it is initialized only once and retains its updated value across all recursive calls.
Step-by-Step Execution Trace:
-
First Call:
f(1)n = 1, andiis initialized to1.- The condition
n >= 5() is false. n = n + i.i++becomes2.- Calls
f(2).
-
Second Call:
f(2)n = 2, andiis currently2.- The condition
n >= 5() is false. n = n + i.i++becomes3.- Calls
f(4).
-
Third Call:
f(4)n = 4, andiis currently3.- The condition
n >= 5() is false. n = n + i.i++becomes4.- Calls
f(7).
-
Fourth Call:
f(7)n = 7.- The condition
n >= 5() is true. - The function immediately returns
n, which is7.
Thus, the value returned by f(1) is 7.
Free practice · Your answers on this page are not saved.
