Remember in elementary school how there was always that one topic that the kids in the grade above would warn you about? They’d whisper horror stories about learning multiplication or cursive (am I aging myself here?) at the bus stop, sending a chill into the students in the grades below.
Recursion is that topic for many programmers. It comes in whispers and horror stories. But the thing is, just like cursive and multiplication, it becomes much easier with practice. Don’t get me wrong — I still have to practice explaining it out loud in order to understand what I’m doing. But hey, we all did multiplication on our fingers at one point.
What is recursion?
A recursive function is one that calls itself. It’s often shown as nesting dolls or a picture of a picture of a picture.
I like to think of recursion as crochet. You loop into the same yarn over and over until you hit a case where it’s no longer necessary.
But how does it work?
Let’s take a look at a practice case:
float _pow_recursion(float x, float y)
if (y == 0)
if (y < 0)
return (_pow_recursion(x, y + 1) / x);
return (_pow_recursion(x, y - 1) * x);
This recursive function multiplies x to the power of y.
Whenever the function hits one of the recursive calls, it will reenter the recursive function. This loop will continue until it reaches the base case where y == 0.
Each time the function goes through the recursive loop, it adds to the stack. A stack is first in, first out, meaning that the first set of values is pushed to the bottom of the stack. All items are popped from the top of the stack.
Now that we have the pieces together, let’s try to walk through a real example with x = 3 and y = 3.
When we go through the loop, we end up building the following stack:
As you can see, we end with the answer that 2 to the power of 2 is 4.
Now take another breath. You’ve got this.