Consider the following C function: int f(int n) { static int i = 1; if (n >=…
2024
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 f(1) is:
- A.
5
- B.
6
- C.
7
- D.
8
Attempted by 105 students.
Show answer & explanation
Correct answer: C
The function is called as f(1).
The variable i is static, so it is initialized only once and retains its updated value across recursive calls.
Call 1:
n = 1, i = 1
n < 5, so n = n + i = 1 + 1 = 2
i becomes 2
Call f(2)
Call 2:
n = 2, i = 2
n < 5, so n = n + i = 2 + 2 = 4
i becomes 3
Call f(4)
Call 3:
n = 4, i = 3
n < 5, so n = n + i = 4 + 3 = 7
i becomes 4
Call f(7)
Call 4:
n = 7
Since n >= 5, return 7.
Therefore, f(1) returns 7.