2017-03-23

Recursion

What is Recursion?

            A function calls itself is called recursion. Recursion is a useful technique. it is shorter and easier to write.


Example:

Factorial problems using Recursion.

      Java
  1. int fact(int n){
  2.      if(n==1)
  3.         return 1;
  4.      else if(n==0)
  5.         return 1;
  6.      else return n*fact(n-1)
  7. }
  8. fact(5)


     Python
  1. def fact(n):
  2.       if n==0:
  3.           return 1
  4.       return n*fact(n-1)
  5. print(fact(5))
    

Explanation:
       
           5*fact(5-1)                   5*return value 24= 120 final result 
                4*fact(4-1)              4*return value 6  = 24
                    3*fact(3-1)          3*return value 2  = 6
                        2*fact(2-1)      2*return value 1  = 2
                           1*fact(1-1)    return 1

Each recursive call makes a new copy of that method in memory. Memory removed for that method once it return.

No comments:

Post a Comment