Consider the following C function:
int f(int n)
{
static int r = 0;
if (n <= 0) return 1;
if (n > 3)
{ r = n;
return f(n-2) + 2;
}
return f(n-1) + r;
}
What is the value of ?
View worked solution
Answer: D
To find the value of , we trace the recursive calls while keeping track of the static variable . Since is static, it retains its value across function calls and is initialized to only once.
- Call : Since , the static variable is updated to . The function returns .
- Call : Since , it executes the last statement and returns .
- Call : Similarly, returns .
- Call : Returns .
- Call : Since , it returns .
Now, substituting the values back:
Thus, the value of is 18.
Free practice · Your answers on this page are not saved.
