Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Recursion Problem  RSS feed

Campbell Ritchie
Posts: 55292
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Dave DiRito:
Campbell, apparently our time zones are several hours apart as I am only just now seeing your posts (5:30 AM, 4/24). Yes, they must be

Yes, the code does work for negative numbers I believe because it's always multiplying a negative number by a positive as it goes through the recursive cycle. Yes.

Using the ? : notation makes it even more elegant. Am I correct in reading it as "If i equals 0, then return 0, else do the recursion loop"? Yes. There are lots of Java methods shorted by using "?:". Look up the code for java.lang.Math#abs (find in your Java installation folder, and unzip it then->java->lang.)

I am not familiar with the call stack notation you posted, so I can't really interpret it. Thanks to working through this problem with your and Paul's help especially, I do have a better understanding of recursion.

I understand that each method call stacks up on the one before until it reaches the stop point (in this case when i == 0). Then it unwinds by returning it's value (result, in this case) to the one previous to it in the stack until it gets down to the first one which returns it's value to wherever it was called from in the first place (in my program, that would be the main method). Yes.

Is that a correct understanding of it?

Yes, I think you are correct in all points now. It was obviously painful, but you will remember how to do it next time you have a recursive problem.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!