3

I'm working to understand recursion more in depth and I'm struggling with WHY it works the way it does. I know that this function returns the square of the previous return (2, 4, 16, 256, etc.), but I'm wonder how it gets the answer.

My understanding of recursion is that it iterates back down to the base case, but that leads me to believe that it would eventually always return the base case. How does it work its way back up to returning something new every time?

int p1a(int num) {
   if (num == 1) { return 2; }
   else {
      return pow(p1a(num-1), 2); 
   }
}

Here's an example of my thinking

num = 3
passes through the base case and hits pow(p1a(num-1), 2)
moves back to the start
again passes through the base case and hits pow(p1a(num-1), 2)
at this point, num = 1, so it would return 2

How is it working its way back up to return 16? I understand what the function returns, but I'm stuck on the process of getting there.

2
  • 2
    While a good CS question, it's not appropriate for SO - understanding CS concepts should be done on a site specific to that subject. The SO Modus Operandi is to solve your problems, not explain to you how to create them :) Commented Nov 12, 2014 at 20:55
  • 2
    To picture what's happening in recursion, it's helpful to view each call to the recursive function as a call to a unique function. In other words, on the first pass you call p1a then on the next pass you call p1b, then p1c and so forth. Now there is no recursion to muddy your thinking. It's just a chain of function calls. Commented Nov 12, 2014 at 20:55

1 Answer 1

3

You're thinking about the steps linearly, while the execution is actually nested (represented by indenting):

call p1a(3)
    call p1a(2)
        call p1a(1)
            return 2
        return pow(2, 2)
    return pow(4, 2)

So the final return returns the value 16.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.