| Author |
returning a value from a method with recursion
|
Mahendra Kariya
Greenhorn
Joined: Aug 25, 2008
Posts: 26
|
|
I coded this method.
On running this method by passing any positive parameter it should return 0. But it is returning -1.
WHY?
|
 |
Sean Clark
Rancher
Joined: Jul 15, 2009
Posts: 377
|
|
Hey,
This method will always return -1 to wherever it is called from unless the input value is 0 (then it returns 0).
What is it that you are trying to do?
Sean
|
I love this place!
|
 |
Mahendra Kariya
Greenhorn
Joined: Aug 25, 2008
Posts: 26
|
|
Sean Clark wrote:
This method will always return -1 to wherever it is called from unless the input value is 0 (then it returns 0).
Yes. But at some point of time, input value will be 0.! Then, it should return 0.
|
 |
Steve Fahlbusch
Ranch Hand
Joined: Sep 18, 2000
Posts: 491
|
|
You have to remember that there are as many returns as there are calls. so
call 1 --- test(1)
not 0
call 2 --- test(0)
is 0
return 0
-- back in call 1
return -1
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Mahendra Kariya wrote:
Sean Clark wrote:
This method will always return -1 to wherever it is called from unless the input value is 0 (then it returns 0).
Yes. But at some point of time, input value will be 0.! Then, it should return 0.
And it does return 0 when n is 0. However, if n is not 0, the return value of the recursive call is completely ignored.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Sean Clark
Rancher
Joined: Jul 15, 2009
Posts: 377
|
|
Mahendra Kariya wrote:
Sean Clark wrote:
This method will always return -1 to wherever it is called from unless the input value is 0 (then it returns 0).
Yes. But at some point of time, input value will be 0.! Then, it should return 0.
Yes it does return 0, but because of where you have put the code
for every recursion it will get the value returned (do nothing with it) and then return -1.
Does that make sense?
Sean
|
 |
 |
|
|
subject: returning a value from a method with recursion
|
|
|