Consider the following C function: int f(int n) { static int i = 1; if(n >= 5)…
2008
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 320 students.
Show answer & explanation
Correct answer: C
The function uses a static variable i initialized to 1, which retains its value across recursive calls. When f(1) is called: n=1, i=1. Since 1 < 5, n becomes 1+1=2 and i increments to 2. The function calls f(2). Inside f(2): n=2, i=2. Since 2 < 5, n becomes 2+2=4 and i increments to 3. The function calls f(4). Inside f(4): n=4, i=3. Since 4 < 5, n becomes 4+3=7 and i increments to 4. The function calls f(7). Inside f(7): n=7, i=4. Since 7 >= 5, the function returns 7.