Recursion

 

what is recursion in programming and how does it work?




Recursion is a technique widely used in computer programming and consists of a function calling itself. The classic example is the function that calculates the factorial of a number. A factorial consists of multiplying a natural number by the previous number, and this in turn by the previous number, and so on until the number 1 is reached. For example, the factorial of 8 would be the result of multiplying 8 by 7, then by 6 and so on until you get to one.

I will show a python code fragment as an example below:


the function is passed a value and will be factored out. an if will be used to check the base case, the base case is the moment where the recursion will stop and the recursive case will subtract at each turn.
here is a more detailed example of what it is doing:


it will pass the 5 and it will check multiple times if this value is equal to one and if not it will subtract it and multiply it by this same value subtracting 1 and so on until it reaches 1 and the base case is fulfilled. 

what happens if there is no base case? if there were no base case it would simply fulfill base case and not stop as if it were in an infinite loop causing things like this:


This is how recursion works, in this article I try to explain it in a simple and graphical way for a better understanding.


Comentarios