How Do You Find The Factorial Of A Number In Java
Chapter:
Miscellaneous
Last Updated:
02-06-2023 05:03:38 UTC
Program:
/* ............... START ............... */
import java.util.Scanner;
public class FactorialCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
scanner.close();
long factorial = calculateFactorial(number);
System.out.println("Factorial of " + number + " is: " + factorial);
}
public static long calculateFactorial(int number) {
if (number < 0) {
throw new IllegalArgumentException("Number cannot be negative.");
}
long factorial = 1;
for (int i = 2; i <= number; i++) {
factorial *= i;
}
return factorial;
}
}
/* ............... END ............... */
Output
Enter a number: 5
Factorial of 5 is: 120
Notes:
-
The program takes input from the user for a number.
- It calculates the factorial of the given number using a loop.
- The factorial is calculated by multiplying all the numbers from 2 up to the given number.
- The calculated factorial is stored in a variable, Finally, the program displays the factorial of the number to the user.
Tags
How do you find the factorial of a number in Java #Write a Java program to find the factorial of a number