Return values and Recursion

• 11-14-2010, 01:28 PM
blug
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!
• 11-14-2010, 01:34 PM
Fubarable
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, 01:45 PM
blug
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!
• 11-14-2010, 01:51 PM
Fubarable
..... :)
Don't you just love the "eureka" moment?
• 11-14-2010, 01:55 PM
blug
Sure do =)