The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+14 votes
1.4k 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$
asked in Programming by Veteran (59.5k points)
edited by | 1.4k 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.

1 Answer

+22 votes
Best answer

The answer is D.

$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.

answered by Boss (19.7k points)
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
+4
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..
Answer:

Related questions



Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

38,039 questions
45,534 answers
131,819 comments
48,853 users