Calculate and print the factorial of a given number using java

import java.util.Scanner;

public class FactorialCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a non-negative integer: ");
        int n = scanner.nextInt();
        long factorial = calculateFactorial(n);
        System.out.println("Factorial of " + n + " is: " + factorial);
        scanner.close();
    }

    private static long calculateFactorial(int num) {
        if (num == 0 || num == 1) {
            return 1;
        } else {
            return num * calculateFactorial(num - 1);
        }
    }
}

 

Post your Answer