jeudi 7 novembre 2019

Java factorial value changes when return is not 1

If the if condition return is something other 1, then the factorial value changes.

As I understand return is way to stop the program. But how is the if statement return is being involved with factorial return statement?

Here is the if condition:

    if (value == 1) {
       // return 0 will cause the factorial return to multiple by 0.
       // return 2 will cause the factorial return 48.
        return 1;  
    }

Final code:

public class test {

    public static void main(String[] args) {
        System.out.println(factorial(4));

    }

    private static int factorial(int value) {

        if (value == 1) {
           // return 0 will cause the factorial return to multiple by 0.
           // return 2 will cause the factorial return 48.
            return 1;  
        }

        return factorial(value - 1) * value;

    }

}

Aucun commentaire:

Enregistrer un commentaire