Recursion

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:

  • A base case (or cases): condition to stop the recursion that does not use a recursion to give an answer, otherwise, an infinite loop will occur.
  • A recursive step: a set of rules that reduces all succesive casses towards the base case.

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.

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.

To view or add a comment, sign in

More articles by Maia Iglesias

  • Optimization techniques

    Optimization techniques are essential tools in machine learning, as they help to improve the performance and speed of…

  • Activation Functions

    An activation function is a mathematical function that determines the output of a neural network given an input or set…

  • IoT - Internet of Things

    What is IoT? The internet of Things (IoT) is a concept that describes the connection between physical devices which are…

    1 Comment

Others also viewed

Explore content categories