407 views
2 votes
2 votes
Consider the following recursive function

int gun(int i)
{
if(i>4)
return(2+gun(i-5) + gun(i-2));
return 1;
}

Find the value returned form the gun(15) ?

2 Answers

0 votes
0 votes

gun(15) = 2 + gun(10) + gun(13)

now we find value of gun(10)

gun(10) = 2 + gun(5) + gun(8)

now we find value of gun(5)

gun(5) = 2 + gun(0) + gun(3)

Now gun(0)=1 and gun(3) =1

gun(5) = 2+1+1 = 4

similarly gun(8) = 2 + gun(3) + gun(6)

                       = 2 + 1 + 2 + gun(1) + gun(4) = 2+1+2+1+1 =7

so gun(10) = 2 + 4 + 7 = 13

Now find out gun(13)

gun(13) = 2 + gun(8) + gun(11)

we already know value of gun(8). so we will find value of gun(11)

gun(11) = 2 + gun(6) + gun(9)

           = 2 + ( 2 + gun(1) + gun(4) ) + ( 2 + gun(4) + gun(7) )

           = 2 + 2 + 1 + 1 + 2 + 1 + gun(7)

           = 9 + (2 + gun(2) + gun(5) )

           = 9 +2 + 1 + (2 + gun(0) + gun(3) )

           = 12 + 2 + 1 + 1

so gun(11) = 16

so gun(13) = 2 + 7 + 16 = 25

hence gun(15) = 2 + 13 + 25 = 40

So answer should be 40

Related questions

0 votes
0 votes
1 answer
1
JPranavc asked Nov 22, 2017
400 views
What will be the output? for foo(4) 4332221234 4332221324 43222214 4332211223