Use of Recursion for Repetitive Algorithms

In some cases we may see that in order to compute a given problem we need to do the same procedure several times, which may turn our source code into a nightmare, making it very very long and very easy to get lost into. So for this cases the use of recursion is very important. 

Recursion is a way of programming in wich you use the same function in a function. Yeah, that’s right you can actually make a function call inside itself. The most common example of recursion is the factorial fuction. The factorial function has a definition that is recursive itself. When you want to compute the factorial of a number you can actually define it as the number times the factorial of the number before it. 

Let’s make the example a little easier to understand:

def factorial(n):

      if n == 1: 

            return 1

      else:

           return n * factorial(n-1)

In this case we can see that the factorial function has a factorial function inside it. This helps us recalculate the factorial many many times, until the n takes the value of 1 which is the smallest factorial. So if we want the factorial of 4, we will calculate the factorial of 3, 2 and 1 to help us calculate it.

Recursion is very important to help us simplify problems and give a more cleaner estructurated solution, instead of having chunks and chunks of code for solving the same problem for different scenarios.

The correct usage of rescursion is very important when programming. The usage of functions is other way to simplify some very complex programs. Many times when you see that your main is a giant block of code you should try and see that much of it can be redefined using functions, where much of those lines can become just some function calls.

This is for my  of my 

CC BY 4.0 Use of Recursion for Repetitive Algorithms by Manuel Lepe is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.