• Post Reply Bookmark Topic Watch Topic
  • New Topic

returning a value from a method with recursion  RSS feed

 
Mahendra Kariya
Greenhorn
Posts: 26
Firefox Browser Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 377
Android Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Mahendra Kariya
Greenhorn
Posts: 26
Firefox Browser Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 612
7
Mac OS X Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sean Clark
Rancher
Posts: 377
Android Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!