¿ What is the recursion ?
Recursion is a method where the function resolve a big problem in problems smaller calling itself n times depends of a base case.
Base case:
Is a condition that indicate to method when should be stop.
How it works ?
I’ll explain how works a recursive method with an example
Example
We have the following code in C:
`float _pow_recursion(float x, float y)
{
if (y == 0)
return (1);
if (y < 0)
return (_pow_recursion(x, y + 1) / x);
return (_pow_recursion(x, y - 1) * x);
`
}
This function performance the potency of a number, The first thing that performance this function when is called is verify the base code in this case is if y == 0 (When y = 0 the function stop) otherwise continue and if y < 0 call itself change parameters in this case change the second parameter (y + 1) and return de division the result with x otherwise if y > 0 the same but change de valu of y to (y-1) and multiply with x.
in conclusion:
- verify if (y == 0) to stop
- if (y < 0) divide the result when call itself changing the value y to y + 1 with x
- if (y > 0) multiply x with the result when call itself changing the value y to y + 1
What happend in the stack ?
When the function is call again that’s mean create a new instance of the function, I’ll show images when the function is call
first time:
Second time:
Third time:
And continue n times, When the function arrive to base case it become come back perfomancing all returns until first one and the stack clean, I’ll show you all the steps with images: