Tuesday, January 28, 2020

Recursion in Java

Recursion in Java

A method is known as a recursive method if it invokes itself directly or indirectly(by some other method). Recursive methods must eventually terminate at some point in time. A recursive method has at least one base-case or case upon which, the execution of methods generally halts. Each successive call to itself must be a "smaller version of itself" so that a base case is finally reached. The arguments of the method are made smaller each time of the invocation of the method so that eventually the base case is executed and finishes the recursion process. Actually, the recursive method can execute the simplest version of the problem only. For the larger or complex version, it will further divide the problem into smaller pieces.

factorial with Recursion
Factorial 

Example( calculating the factorial with Iteration)


//Calculating Factorial of a number using
public class Demo {
public static void main(String[] arg) {
    //Iteration
    Demo d=new Demo();
System.out.println(d.factorial(7));
}
int factorial(int num)
{
    int fact=num;//num>=1 only
    for(int counter=num-1;counter>=1;counter--)
    {
        fact=fact*counter;
    }
    return fact;
}
}

Calculating factorial with recursion


public class DemoRecursion {// Factorial by recursion

    public static void main(String[] args) {
    DemoRecursion dr=new DemoRecursion();
    System.out.println(dr.factorial(7));
    }
    int factorial(int num)// recursive method
    {
        if(num<=1)
        {
            return 1;//base case
        }
        else
        {
            return num*factorial(num-1);
        }
    }
}

Video Tutorial