# Thread: Return values and Recursion

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!

2. 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.

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.

4. Member
Join Date
Oct 2010
Posts
26
Rep Power
0

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•