Recursion (Advance Function topic)

Recursion 

When a method calls itself repeatedly and keeps calling itself until it has reached the base case is called recursion 




Why recursion : Shorter and easier to write than iterative code(loops).

#Example:

....main funtion 

n=5;

public int manvik(int n){
                   if(n==0){
                                   return 0;
                        }
                  else{
                         System.out.println(n);
                         return manvik(n-1);//here manvik() method call itself
                    }
}

here,

          return manvik(n-1);
 
manvik() method calls itself so that is Recursive method which calls itself repeatedly and keeps calling itself until it has reached the base case.


Which is better iteration(loops) and recursion
  • both are good in their own work
Recursion 
  • Terminates when a base case is reached.
  • Each recursion call require extra space on the stack (memory) frame.
  • If we get infinite recursion the problem may run out memory and result is stack overflow.
  • Solution to some problem are easier.
Iteration
  • Terminate when condition is false
  • Not require extra memory 
  • Infinite loop goes on forever because Because there is no need of extra memory
  • When some programs become very complex, they are performed by recursion.
Question 

1. WAP to print Fibonacci series using recursion.

static int a = 0;
    static int b = 1;
    public static void main(String[] args) {
        System.out.print(a+" "+b);
        int limit = 5;
        fib(limit-2);
    }
    static void fib(int p){
        if(p==0){
            System.out.println(" series end");
        }
        else{
            int sum = a+b;
            System.out.print(" "+sum);
            a=b;
            b=sum;
            fib(p-1);
        }
    }
#Out put : 0 1 1 2 3 series end

2. WAP to calculate factorial of a number using recursion.

public static void main(String[] args) {
        int a = 5;
        System.out.println(fact(a));
    }
    static int fact(int p){
        if(p==1){
            return p;
        }
        else{
            return p * fact(p-1);
        }
    }
#Out put : 120

3. WAP to reverse integer number using recursion.

static int r = 0;
    public static void main(String[] args) {
        int n = 125;
        System.out.println(rev(n));
    }
    static int rev(int p){
        if(p==0){
            return p;
        }
        else{
            int d = p%10;
            r = r * 10 + d;
            rev(p/10);
        }
        return r;
    }
#Output : 521

4. WAP to find the sum of positive integer number Using recursion.
    n = 10 (10+9+8+7+6+5+4+3+2+1) = 55

public static void main(String[] args) {
        int n = 10;
        System.out.println(fact(n));
    }
    static int fact(int p){
        if(p==0){
            return p;
        }
        else{
            return p + fact(p-1);
        }
    }
#Output : 55

Comments