Consider the following C function, what is the output?
#include <stdio.h> 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;
} int main()
{ printf ( "%d" , f(5));
} |
(A) 5
(B) 7
(C) 9
(D) 18
Answer: (D)
Explanation:
f(5) = f(3)+2 The line "r = n" changes value of r to 5. Since r is static, its value is shared be all subsequence calls. Also, all subsequent calls don't change r because the statement "r = n" is in a if condition with n > 3. f(3) = f(2)+5 f(2) = f(1)+5 f(1) = f(0)+5 f(0) = 1 So f(5) = 1+5+5+5+2 = 18