Results 1 to 5 of 5
Thread: Return values and Recursion
- 11-14-2010, 12:28 PM #1
Member
- Join Date
- Oct 2010
- Posts
- 26
- Rep Power
- 0
Return values and Recursion
Hello Hello, I have confused myself quite a bit.
I was asked to make a method, somewhat like the inbuilt pow method with the class Math, except it needed to output an int value rather than a double value.
I actually found it fairly easy...
public static int getPow(int number, int power){
if (power == 0){
return 1;
}
else{
return getPow(number, power - 1) * number;
}
}
I was looking at the code however, and I was thinking... how the heck does it work? I know it may sound weird, but I created it, and then I realized I don't even get it.
I understand how recursion works and how stacks work and stuff. The thing which confuses me is this line
return getPow(number, power - 1) * number;...
It might be really simple, but what is getPow(number, power - 1) and how can that be returned as a value? I understand that it is calling upon itself, but what value is it returning? I don't know, this is really screwing with my head, and I don't know what the hell is happening with return values.
Thanks for any help however!
-
The method returns an int, so if you return a call to the method, you are in fact returning an int. This method will keep calling itself recursively until the end case is reached, power is 0, and then all the returns will cascade but in the opposite order from how they were called.
- 11-14-2010, 12:45 PM #3
Member
- Join Date
- Oct 2010
- Posts
- 26
- Rep Power
- 0
OH WAIT! I get it now! I had a big post trying to explain what I was having trouble with but by actually going through each individual stack I actually figured it out...
I didn't consider the 1 value at the top of the stack, kind of creates a domino effect as it cycles down the stacks.
Thanks for the help, was very helpful!Last edited by blug; 11-14-2010 at 12:48 PM.
-
..... :)
Don't you just love the "eureka" moment?
- 11-14-2010, 12:55 PM #5
Member
- Join Date
- Oct 2010
- Posts
- 26
- Rep Power
- 0
Similar Threads
-
Method to return values
By puchatek in forum New To JavaReplies: 4Last Post: 11-11-2010, 09:27 AM -
Looking at the values in the stack during recursion
By luke in forum New To JavaReplies: 0Last Post: 10-05-2010, 08:12 PM -
Help with Recursion and return statement
By nicolek808 in forum New To JavaReplies: 3Last Post: 09-10-2009, 10:02 AM -
Using functions that return values?
By Megapixelz in forum New To JavaReplies: 1Last Post: 04-30-2008, 04:07 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks