Recursion

Recursive programming is a procedure in which a method calls itself, so that a problem is solved more and more with each method call. This continues until the problem is reduced to a very simple case.

Some tasks in computer science can be solved well by reducing a large problem step by step to smaller and smaller problems of the same kind until simple (trivial) solutions arise . From this finally the solution of the original large problem is put together.

Syntax

modifiers return_type method_name(type parameter) {
    // code to be executed
    return method_name(type parameter)
}

Example: factorial

public class FactorialRecursion {
    public static int factorial(int number) {
        if (number < 2) {
            return 1;
        } else {
            return number * factorial(number - 1);
        }
    }

    public static void main(String[] args) {
        int factorial = factorial(8);

        System.out.println("factorial of 8 is " + factorial);
    }
}
Output
factorial of 8 is 40320

Example: fibonacci

public class FibonacciRecursion {
    public static int fibonacciAlgorithm(int number) {
        if (number == 0 || number == 1) {
            return number;
        } else {
            return fibonacciAlgorithm(number - 1) + fibonacciAlgorithm(number - 2);
        }
    }

    public static void main(String[] args) {
        int fib = fibonacciAlgorithm(10);

        System.out.println("fibonacci number of the number 10 is " + fib);
    }
}
Output
fibonacci number of the number 10 is 55