Recursion in Java

Recursion In Java

When the method calls itself, it is called recursion. This will break complicated problems into easier and uses less code.

Adding two numbers is easy but adding a range of numbers is more complicated. You can easily solve this problem with recursion.

Example Of Recursion

public class Main {
    public static void main(String[] args) {
        int total = sum(3);
        System.out.println("Total is "+total);
    }
    public static int sum(int num) {
        if (num > 0) {
            return num + sum(num - 1);
        } else {
            return 0;
        }
    }
}
Show Output