How can Java use recursion to calculate factorial?

To calculate a factorial, you can use a recursive function. Here is an example of Java code that calculates a factorial using recursion.

public class Factorial {
    public static int factorial(int n) {
        if (n == 0 || n == 1) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }

    public static void main(String[] args) {
        int n = 5;
        int result = factorial(n);
        System.out.println("Factorial of " + n + " is: " + result);
    }
}

In the code above, the factorial() function is a recursive function that takes an integer parameter n and returns the factorial of n. If n equals 0 or 1, the function directly returns 1. Otherwise, the function calculates the factorial of n by calling itself, which is n * factorial(n – 1). Finally, the main() function calls the factorial() function to calculate and print the result. Running the above code will output:

Factorial of 5 is: 120

This indicates that the factorial of 5 is 120.

bannerAds