Recursion in a nutshell
Recursion is a programming technique used in procedures, functions, or algorithms.?
This technic defines a termination condition of successive calls of itself. The purpose of each inner call is to segment a problem by accessing each time with different parameters according to logic conditions that allowed us to meet the termination condition. Once the condition is reached, proceeds to return from the last one called to the first.
Let's analyze the next function to understand the procedure:
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 calculates the value of a number raised to a power. The parameter x represents the base and y is the exponent. Simplifying we must multiply x by itself y times to find the result.
Example 1: 5^3
x = 5 y = 3
Result: 5 * 5 * 5 = 125
领英推荐
Example 2: 5^-3
x = 5 y = -3
Result: 1/5 * 1/5 * 1/5 = 0,008
Regardless of y being positive or negative, the parameter gonna work as a counter of repetitions.
In a positive instance, every time the function is called the y parameter should be sent decreased one time (y - 1), otherwise should be sent incremented one time (y + 1). This leads us to the termination condition when the zero is reached, in other words, when y is equal to zero there is no longer a need to call the function.
Going back in the callings will show each x multiplication with the cumulative result of the recursion.
Thanks for reading!