Recursion

Recursion is the process in which a function calls itself either directly or indirectly. It is needed when the output is based on a particular instance of similar logic or pattern.


The function that calls itself is called an recursive function.

Now let us use recursion to find out the value of factorial of 6. Please note that every recursive function has an terminating point where the function returns some constant value instead of calling itself. So for our factorial problem our function could return 1 as soon as the number becomes equal to zero ( since factorial of 0 is 1 ). We need not worry about negative numbers , as their factorial is not defined.


The illustration below explains the code for our problem.

basic components of a recursive function.

Now we understand every statement of our recursive function. Now let us see the whole recursive cycle and understand how a recursive function works. This is explained in the illustration below.

flow of logic through recursion.

Now let us run the code in the editor below.

def factorial(n):
    if n<0:
        return 'factorial not defined'
    if n==0:
        return 1
    else:
        return n*factorial(n-1)
    print(factorial(6)) 
output:
720

Another very popular application of recursion is the fibonacci series. Essentially in this series , every term is sum of previous two terms. The series goes something like this : 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 ...


Let us take an example where we return nth term of the fibonacci series ( using recursion ).

def fibo(n):
    if n<=0:
        return 0
    if n==1 :
        return 1
    else:
        return fibo(n-1)+fibo(n-2)
        
print(fibo(20))
output:
6765




Popular Tutorials

Creative Commons Licence
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.