Recursion in a nutshell

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.

Recursion image

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.

Increasing & decreasing

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.

No hay texto alternativo para esta imagen
No hay texto alternativo para esta imagen

Going back in the callings will show each x multiplication with the cumulative result of the recursion.

Thanks for reading!

要查看或添加评论,请登录

Angela Vergara Salamanca的更多文章

  • How the network delivers information to our devices?

    How the network delivers information to our devices?

    We get used to the idea of typing in a web browser any search, but how to deliver that information to our computers…

  • IoT Basics

    IoT Basics

    The internet of things, widely known as IoT, is a system of unique identified devices interrelated to transfer data…

  • C Static Libraries : Collection of files

    C Static Libraries : Collection of files

    A library in C is a collection of files meant to be used by other programs. The library consists of two types of files,…

  • GCC - How to get an executable file?

    GCC - How to get an executable file?

    In the early 1970s, Dennis Ritchie developed the C programming language as an improvement of B. B by Ken Thompson was…

    1 条评论

社区洞察

其他会员也浏览了