What will be the output of the following code? int f(int n) { static int a =…
2024
What will be the output of the following code?
int f(int n)
{
static int a = 0;
if (n <= 0)
{
return 1;
}
if (n > 3)
{
a = n;
return f(n - 2) + 2;
}
return f(n - 1) + a;
}
int main()
{
printf("Result:%d", f(5));
return 0;
}- A.
19
- B.
9
- C.
12
- D.
18
Attempted by 2 students.
Show answer & explanation
Correct answer: D
A variable declared static inside a function is initialized only once and then retains its value across every subsequent call to that function — it is not reset to its initial value on re-entry. It is only changed when an explicit assignment statement inside the function executes. So tracing a recursive function that uses a static variable means tracking two things at once: which return expression each call takes, and the CURRENT value the static variable holds at the moment that expression is evaluated (not its value when the function was first entered).
Trace f(5) call by call, noting exactly when a changes:
f(5): n = 5 > 3, so a is set to 5, and the call returns f(3) + 2.
f(3): n = 3 is neither <= 0 nor > 3, so it takes the final line and returns f(2) + a — and a already holds 5, so this is f(2) + 5.
f(2): n = 2 falls into the same case, returning f(1) + a = f(1) + 5.
f(1): n = 1 falls into the same case again, returning f(0) + a = f(0) + 5.
f(0): n = 0 <= 0, so this is the base case — it returns 1 directly, with no further recursive call.
Now unwind the calls from the base case back up:
f(1) = f(0) + 5 = 1 + 5 = 6
f(2) = f(1) + 5 = 6 + 5 = 11
f(3) = f(2) + 5 = 11 + 5 = 16
f(5) = f(3) + 2 = 16 + 2 = 18
Cross-check independently: a is assigned exactly once, to 5, and this fixed value is added exactly three times — once each in f(3), f(2), and f(1) — on top of the base value of 1 returned by f(0). That gives 1 + 5 + 5 + 5 = 16, and the single outer +2 contributed by the very first call (f(5) itself) brings the final result to 18.