Write a Java Program to find the factorial of a given number.
Certainly! Below is a simple Java program that calculates the factorial of a given number using both iterative and recursive methods. You can choose either method based on your preference.
import java.util.Scanner;
public class FactorialCalculator {
// Iterative method to calculate factorial
public static long factorialIterative(int n) {
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// Recursive method to calculate factorial
public static long factorialRecursive(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorialRecursive(n - 1);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a non-negative integer: ");
int number = scanner.nextInt();
if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
// Calculate factorial using iterative method
long iterativeResult = factorialIterative(number);
System.out.println("Factorial of " + number + " (Iterative): " + iterativeResult);
// Calculate factorial using recursive method
long recursiveResult = factorialRecursive(number);
System.out.println("Factorial of " + number + " (Recursive): " + recursiveResult);
}
scanner.close();
}
}
Scanner
class for user input.factorialIterative(int n)
: This method calculates the factorial using a loop.factorialRecursive(int n)
: This method calculates the factorial using recursion.FactorialCalculator.java
.javac FactorialCalculator.java
.java FactorialCalculator
.