Programming in C
Programming Fundamentals
GATE 2007
Expert
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 f(5)?
- A5
- B7
- C9
- 18
Explanation
f(5): n>3, so r=5, return f(3)+2. f(3): n not>3, return f(2)+r (r=5). f(2): return f(1)+r(5). f(1): return f(0)+r(5). f(0): n<=0, return 1. So f(1)=1+5=6, f(2)=6+5=11, f(3)=11+5=16, f(5)=16+2=18.
Source: GATE CS 2007 (2007)
This question is part of a 15-day revision cycle — sign in and Project Forge will bring it back the day before you'd forget it.