File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes returning a value from a method with recursion Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "returning a value from a method with recursion" Watch "returning a value from a method with recursion" New topic
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
    
    2

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
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: returning a value from a method with recursion
 
Similar Threads
what can i do to make my code right???
Compilation Error
Iterative Fibonacci Method Problem
Fibonacci Algorithms and their different manifestations. Which is the best?
recursive function call program