What is Recursion?

In simple words, Recursion is a function that calls itself until it meet its basecase. For eg:

public class Main {

    public static void main(String[] args) {
        hello(5);
    }

    public static void hello(int n){
        if (n == 0){
            System.out.println("world");
        }else {
            System.out.println("hello");
            n--;
            hello(n);
        }
    }
}

// output
hello
hello
hello
hello
hello
world

In above example we call hello function 5 time and decremented every by -1( which n–) until the n become 0. Whenever you use Recursion it is important that you have a basecase. If you don’t have a basecase, the function will run in infinite time and get error.

The best way to practice Recursion is write a program that tell what is factorial for n number.

To link to the codechef factorial problem. https://www.codechef.com/problems/FCTRL2

Leave a comment