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);
}
}
}
Enter a number: 7
Factorial of 7 is 5040
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
.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)
.