DEV Community

Buddika Abeykoon
Buddika Abeykoon

Posted on

Recursive Factorial Program in Java

public class RecursiveFactorial {
    static int factorial(int n) {
        if (n == 0 || n == 1) {
            return 1; // Base case
        } else {
            return n * factorial(n - 1); // Recursive call
        }
    }

    public static void main(String[] args) {
        int number = 5;

        int result = factorial(number);

        System.out.println("Factorial of " + number + " is: " + result);
    }
}
Enter fullscreen mode Exit fullscreen mode

This program is used to calculate the factorial of a number using recursion in Java. Recursion means a method calls itself repeatedly until a stopping condition is reached. In this program, the factorial() method checks whether the number is 0 or 1. If it is, the method returns 1, because the factorial of 0 and 1 is always 1. This is called the base case and it stops the recursion. If the number is greater than 1, the method multiplies the number by the factorial of the previous number using factorial(n - 1). For example, when the number is 5, the calculation happens as follows,
5!=5×4×3×2×1=120
In the main method, the number 5 is stored in a variable, the factorial() method is called, and the final answer is printed on the screen. The output of the program is “Factorial of 5 is: 120”.

Top comments (0)