1k views

Consider the following C function:

int f(int n)
{
static int r = 0;
if (n <= 0) return1;
if (n > 3)
{   r = n;
return f(n-2) + 2;
}
return f(n-1) + r;
}


What is the value of $f(5)$?

1. $5$
2. $7$
3. $9$
4. $18$
edited | 1k views

Can anyone explain why f(5) will not execute  return f(n-1) + r;?

unreachable code once it retruns completly its stack

I think there should be an else in lile 9.

int f(int n)
{
static int r = 0;
if (n <= 0) return1;
if (n > 3)
{   r = n;
return f(n-2) + 2;
}
else return f(n-1) + r;
}
@mint the "else" doesn't matter, since we are using "return f(n-2)+2". Your else part becomes unreachable.
How it becomes unreachable ? Plz explain a bit.

$f(5) = 18.$

$f(3) + 2 = 16 + 2 = 18$

$f(2) + 5 = 11 + 5 = 16$

$f(1) + 5 = 6 + 5 = 11$

$f(0) + 5 = 1+5 = 6$

Consider from last to first. Since it is recursive function.

edited by
I don't understand one thing

Each time f() gets called 'r' will be initialised to zero

So we should add 0 not 5

No, it's correct to add 5.

Reason :

• static keyword is used to declare & initialize ' r '.
• Since static variables are declared & initialized only ONCE; so despite of several function calls, the static variable will retain it's previous value/scope.
before  statement returnf(n-1)+r;

there should be else ?? or if not then how to conclude that f(5) will not execute this line
All statements after a return statement are not executed. So, if a return statement is inside "if", there is no need to give "else" following it.
After returning of f(3) it will come out of the if statement  and again execute f(n-1)+r becoz its not in else part.

Correct me if i am wrong
After calculating 18 , can't we again start doing f(4) +5 ? Plz anyone explain
I think it is not in a while loop to execute for n=4,3 etc..