Search code examples
javarecursionfactorial

Java - What is the order of operations in this recursion?


I seem to be a little stuck on really grasping recursions so I can use them.

This is the example I found on a tutorial.

I want to verify to see if I am understanding this correctly.

public class SolveRecursion {



public void recursionPerform(){

System.out.println(fact(4));


}
public static long fact(long n){

    if (n <= 1){
        return n;
    }
    else{
        return n * fact(n-1);
    }

}
}

Let us set n to 4.

In that case, is this what happens? (Sorry for the confusing format, I did my best)

(Is n(4) <=1, No), Else, n(4) * (Is (n-1=3) <=1, No), Else, n(3) * (Is (n-1=2) <= 1, No), Else * (Is (n-1<=1), Yes) * n(1)


Solution

  • Here's the order of operations:

    n = 4
    Is 4 <= 1? No
    4 * fact(3)
        n = 3
        Is 3 <= 1? No
    4 * 3 * fact(2)
            n = 2
            Is 2 <= 1? No
    4 * 3 * 2 * fact(1)
                n = 1
                Is 1 <= 1? Yes, return 1.  // Base Case
    4 * 3 * 2 * 1
    24