Reputation: 83
First Code: a = 5
if (a==0)
return 1;
return a * xample(a-1);
My tracing:
5==0 FALSE skip return 1 return 5 * xample(5-1) so, a = 4
go back inside the method 4==0 FALSE skip return 1 return 5 * xample(4-1) so, a = 3
go back inside the method 3==0 FALSE skip return 1 return 5 * xample(3-1) so, a = 2
go back inside the method 2==0 FALSE skip return 1 return 5 * xample(2-1) so, a = 1
go back inside the method 1==0 FALSE skip return 1 return 5 * xample(1-1) so, a = 0
go back inside the method 0==0 TRUE return 1
so last value is 1, how come the real last value is 120?
Second Code: a = 5
if (a<1)
return 1;
else
return a + xample(a/5);
how come the answer is 7?
Third Code: a = 5
a--;
if (a>0)
{
xample(a);
}
return a;
How come the answer is 4???
Upvotes: 0
Views: 66
Reputation: 393821
In the following code :
if (a==0)
return 1;
return a * xample(a-1);
If a is 5 :
return 5 * xample (5 - 1) =
5 * 4 * xample (4 - 1) =
5 * 4 * 3 * xample (3 - 1) =
5 * 4 * 3 * 2 * xample (2 - 1) =
5 * 4 * 3 * 2 * 1 * xample (1 - 1) =
5 * 4 * 3 * 2 * 1 * 1 = 120
Upvotes: 3