Recursion
Recursion is the process in which a function calls itself directly or indirectly, using recursive algorithms certain problems can be solved quite easly. Some properties of the recursive method are:
The utility of resolving problems using recursive functions is that we can save some lines of code and are often easy to understand.
Now take a look at this recursive function and let's explain recursion in a more detailed way:
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);
}
In this example the function calculates "x" raised to the power of "y" using the recursive method.
First we have the definition of the function which receives two parameters, "x" which is the base of the power and "y", the exponent or power y.
Recommended by LinkedIn
float _pow_recursion(float x, float y)
Inside the function (between the "{}") we have the first condition, this one means that if "y" is equal to 0, the function will return 1, since any number powered to 0 is equal to 1.
if (y == 0)
return (1);
The next condition states that if the power passed is negative, the function will return a new call of the function itself modifying the previously sent parameters, which will be "x" and "y" + 1 divided by "x", these will be pass to the funtion as new parameters.
if (y < 0)
return (_pow_recursion(x, y + 1) / x);
The last condition will be taken if none of the previous conditions are met, that if the exponent is different from 0 and is not negative. The function will call itself with new parameters, that will be "x" and the value of "y" - 1 multiplied by "x", these will be the new parameters that will be passed to the fuction.
return (_pow_recursion(x, y - 1) * x);
In both prior cases when the function reaches 0 it should return the corresponding result of the power.