Search code examples
javarecursionfactorial

Recursion Tutorial


I am learning Java from a book, and come across a chapter regarding recursion using a factorial example.

//A simple example of recursion

package tutorials;

class Factorial {
// this is a recursive method
int fact (int n) {
    int result;

    if(n==1) return 1;
    result = fact(n - 1) * n;
    return result;
  }
}

class Recursion {
    public static void main(String args[]) {
        Factorial f = new Factorial();

        System.out.println("Factorial of 3 is " + f.fact(3));
        System.out.println("Factorial of 4 is " + f.fact(4));
        System.out.println("Factorial of 5 is " + f.fact(5));
    }
}

The result this piece of code gives is "Factorial of 3 is 6" and "Factorial of 4 is 24"

What i don't understand is what is happening in the class Factorial and why *n is not calculated immediately. The book does not do a very good job of explaining this so i thought i would ask any experienced programmers for help.


Solution

  • If you invoke fact(5), here is how it will work:

    fact(5)
        5*fact(4)
            4*fact(3)
                3*fact(2)
                    2*fact(1)
                        2*1=2 //(since if n==1, 1 is returned directly
                    result=2
                result=3*2
            result=4*3*2
        result=5*4*3*2
    result=120
    

    Recursion simply means you invoke a method within itself, usually after manipulating the argument to suit your end result (n - 1 in this case). You also make sure you define a terminal condition (n==1 in this case). Internally, the variables are pushed on to a stack to be remembered for every invocation, but that's probably a discussion for another day