Inception

--Originally published at Fundamentos de Programación

inception

Use of recursion for repetitive algorithms.

Sometimes we will be in the need to repeat a cerain procedure several times but if we write the same line of code multiple times it will make pur code hard to read and it can get confusing. But for that we have a solution: Recursion

lmzz52m_700wa_0

Recursion is a method in which we call the same function inside a function. Yes it is possible. We can see some common examples like when we are looking for the max common divisor with the Euclides method. It will be something like this:

rw9zy9m_700wa_0

def obtener_mcd(a, b):
if(b==0):
return a
else:
return obtener_mcd(b, a % b)

wwlnamr_700wa_0

Or when we want to obtain a factorial:

def factorial(n):

if n==1:

return 1

else:

return n*factorial(n-1)

In both we can see the function inside the function. We just change the values in the parameters with the ones we obtain with the first iteration.

1d43qdr_700wa_0

It is very important to know how to use recursion to have better looking codes and efficient ones.

This is an excelent video to help you understand if you don’t get quite well how can a method call itself and what does it actually happens when it does.

Keep up with the code!

Follow me on twitter: @danigguemez

Check out more info in this sites:

http://www.aprenderaprogramar.com/foros/index.php?topic=1161.0

Use of Recursion for Repetitive Algorithms