Recursion in programming? Recursion in programming? Recursion in programming? ...
The objective of this article is to explain the concept of recursion in programming to people who are just learning the term and are not very clear about its usefulness or the key aspects to take into account.
Therefore… What is recursion? In essence, recursion is a function that calls itself to avoid the use of loops and other types of iterators, which allows you to solve certain problems in a more elegant and efficient way in terms of code.
What characteristics or aspects should be taken into account with recursion:
To internalize the concept, I am going to do an example with a recursive function that returns the result of a number raised to any power “n”. This means, in mathematical terms, for example, that 2 to the power of 5 is equal to 2x2x2x2x2, which turns out to be equal to 32. That is, the base, in this case 2, multiplies itself the number of times which indicates the exponent or power, in this case 5 times.
To reinforce the ideas I've expressed above, I'm going to break down the following function:
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);
}
Step by step detail:
Functional case:
If we call the function as in the example, where x = 2 and y = 5, the function would basically do the following:
Recommended by LinkedIn
Non-functional case:
Since this function receives and returns floats, but with each recursion the value of "y" is reduced by 1, then with any float that is not an integer, the exit condition y == 0 will never be met, and therefore , the function will call itself indefinitely, generating a stack overflow.
If we call the function with x = 2 and y = 0.5, the function would basically do the following:
I hope then with this example it has become clear what recursion is and its two main elements to consider: The base condition and the stack. The above concepts are key to ensuring that recursion is successful.
Sources: