Java Recursion

A method that calls itself is referred to be a recursive method in Java.

Mostly, we use recursion technique to perform complex tasks. We can program to use recursion technique, to execute until certain condition is satisfied.

Factorial program with Recursion

class Main {

    int factorial(int n) {
        if (n != 0)
            return n * factorial(n-1);
        else
            return 1;
    }

    public static void main(String[] args) {
        int number = 5, result;
        Main obj = new Main();
        result = obj.factorial(number);
        System.out.printf("Factorial of %d is %d",number, result);
    }
}

Running the above program will provide us with the result as below

Factorial of 5 is 120

In the above program, we have a method factorial() which takes an integer as input and check whether it is not equal to 0. If it is true, then we will multiple the value of n and calls factorial() method with n-1 as parameter.

This will be continued until the value of n is 0. Finally, we multiple all the values like below and return the final result.

5*4*3*2*1

The iteration will look like,

loop 1: 5*factorial(5-1)
loop 2: 5*4*factorial(4-1)
loop 3: 5*4*3*factorial(3-1)
loop 4: 5*4*3*2*factorial(2-1)
loop 5: 5*4*3*2*1

When we use recursive function in a loop, we should be very careful in mentioning the exit condition. If the exit condition of the loop misses, then it will continue to execute till we program terimates.

Note: Recursion typically consumes more memory and are slower in nature.


Most Read