Java Program to find factorial of a number
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a non-negative integer: ");
int number = input.nextInt();
if (number < 0) {
System.out.println("Factorial is undefined for negative numbers.");
} else {
long factorial = calculateFactorial(number);
System.out.println("The factorial of " + number + " is: " + factorial);
}
input.close();
}
// Function to calculate the factorial of a number using recursion
public static long calculateFactorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case: 0! and 1! are both 1
} else {
return n * calculateFactorial(n - 1); // Recursive case
}
}
}
In this program, we take a non-negative integer as input from the user and then calculate its factorial using a recursive function calculateFactorial. The base case is when n is 0 or 1, in which case the factorial is 1. For other values of n, the function calculates the factorial by multiplying n with the factorial of n-1. Finally, the program prints the factorial of the given number.
Sample Output:
Enter a non-negative integer: 5
The factorial of 5 is: 120