0

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

3
  • 1
    Fire up your debugger, single-step through the examples, watch the "call stack" display. That's by far the best way to see how this works. Textual descriptions tend to be very weak in comparison. Commented Feb 19, 2015 at 9:27
  • What part is unclear? Use a debugger to watch what happens when you run the code. If you don't have or know how to use a debugger, stop what you're doing and get one / learn the basics of using one. Using a debugger is a fundamental part of programming, including learning programming. Commented Feb 19, 2015 at 9:29
  • Wait: You're saying you're unwilling to take a few minutes to do the best thing you can do to understand recursion? Due respect, but that seems an odd approach to learning. Commented Feb 19, 2015 at 9:32

1 Answer 1

3

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 
Sign up to request clarification or add additional context in comments.

6 Comments

great!!!! i understand the process of the first code now.... so it only means that when the method is being called again the value of a will change!!! i thought it will remain to 5!!! great!! I gotta understand the other codes!!! thanks...
but wait...... why is it 5 * 4 * 3 * 2 * 1 * 1 ??? it should be 5 * 4 * 3 * 2 * 1 * 0..... because 1-1 is 0.....
@Rae if (a==0) return 1;
by the way, i dont understand how the third code works.... why does it ascends back until 4 when 1-1=0?
@Rae The last code ignores the output of the recursive call, so you can replace it with this equivalent code : a--; return a;
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.