Google News
logo
Java Program to Find Factorial of a Number Using Recursion
In the following example of Java program that calculates the factorial of a number using recursion :
Program :
import java.util.Scanner;

public class Factorial {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = sc.nextInt();
        sc.close();

        long factorial = calculateFactorial(number);
        System.out.println("Factorial of " + number + " is " + factorial);
    }

    public static long calculateFactorial(int n) {
        if (n == 0 || n == 1) {
            return 1;
        } else {
            return n * calculateFactorial(n - 1);
        }
    }
}
Output :
Enter a number: 7
Factorial of 7 is 5040
* In this program, we first read a number input from the user using the Scanner class. We then call the calculateFactorial() method, which takes an integer argument n and returns the factorial of n. The calculateFactorial() method uses recursion to calculate the factorial of n.

* The base case of the recursion is when n is equal to 0 or 1, in which case the factorial is 1. If n is greater than 1, the calculateFactorial() method multiplies n by the factorial of n - 1 using the recursive call calculateFactorial(n - 1).

* Finally, we print the factorial of the input number to the console.