505 views
0 votes
0 votes
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)?

 

Kindly explain how the recursion is working here along with the solution.

2 Answers

0 votes
0 votes

f(5)

n=5 r=0


n=5,r=5

n>3

so,

f(3)+2


n=3

so,

f(2)+r

f(2)+5


f(1)+5


f(0)+5


f(0)=1

so f(5)=18

0 votes
0 votes
f(3)+2 f(2)+r f(1)+r f(0)+r

here one thing is to note that r is static variable when we call f(5) r=n =>r=5

now 5>3 so f(5)=f(3)+2=16+2=18

now f(3) will be called so f(3)=f(2)+r=11+5=16

now f(2) will be called so f(2)=f(1)+r=6+5=11

now f(1) will be called so f(1)=f(0)+r =>1+5=6

f(0)=1

so finally the value of f(5) is 18

Related questions

352
views
1 answers
0 votes
Sambhrant Maurya asked Jul 15, 2018
352 views
211
views
1 answers
0 votes
Sambhrant Maurya asked Jul 15, 2018
211 views
353
views
2 answers
0 votes
Sambhrant Maurya asked Jul 15, 2018
353 views
371
views
2 answers
0 votes
Sambhrant Maurya asked Jul 13, 2018
371 views
A(n){if(n<1)return 1;elsereturn A(n-2) + B (n-1);}B(n){if(n<=1)return 1;elsereturn B(n-1) + A(n-2);}What is the output for A(6)?Please show how the recursion is working here along with the solution.