Recursion, how works?

Esneider Granada Valencia
2 min readJul 5, 2021

Recursion is the process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function.

One of the common recursive function is “factorial(n)” where n is multiplied by itself and decrease by 1 the times that “factorial(n)” is called until n is zero.

To explain this concept (recursion) we are going to see how works the following function:

To start, I’m going to use the above function with the parameters (x = 2, y =3) and we’ll see it’s behavior.

_pow_recursion(2, 3)

Since ‘y’ is a positive number, the second if statement never will be executed.

The first part of the function is asking if ‘y’ is equal to zero, in this case this line is avoid cause right now ‘y’ is 3.

Once the execution is on the next line, the function calls itself giving two arguments, and multiplying by ‘x’(which is equal to 2) the result of the function.

Notice that the variable ‘y’ is decrease by 1 each time that the function calls itself, at least until y == 0, and the multiplication by ‘x’ is stored in the stack.

That means that when the function return a number, this number will be multiplied by each ‘x’ stored in the stack.

Let’s see the execution of the recursive function, stack and finally it’s result.

--

--