1.6k views

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)$?

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

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

0
unreachable code once it retruns completly its stack
0

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;
}
+1
@mint the "else" doesn't matter, since we are using "return f(n-2)+2". Your else part becomes unreachable.
0
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
0
I don't understand one thing

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

So we should add 0 not 5
+4

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.
0
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
+5
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.
0
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
0
After calculating 18 , can't we again start doing f(4) +5 ? Plz anyone explain
0
I think it is not in a while loop to execute for n=4,3 etc..

1
2