Java – Find Factorial of A Given Number
Write a Java program to find a factorial of the given number input by the user.
What is Factorial of Number?
The factorial is represented by the exclamation mark (!). A simple formula to calculate the factorial of a number is
n! = n (n - 1)!
For an example, the factorial of 5 is equivalent to 5 x 4 x 3 x 2 x 1.
Java Program to Find Factorial of a Number
This is a Java program to find the factorial of a Number using for loop. This program prompt user to enter a number and calculate factorial of that number. Then print the factorial of the number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import java.util.Scanner; public class FindFactorial { private static Scanner scanner = new Scanner( System.in ); public static void main(String[] args) { System.out.println("Enter a number: "); String input = scanner.nextLine(); int num = Integer.parseInt( input ); int fact = 1; for (int i = 1; i <= num; i++) { fact = fact * i; } System.out.println("The factorial of " + num + " is " + fact); } } |
Compile and run program:
javac FindFactorial.java java FindFactorial
Result:
Enter a number: 5 The factorial of 5 is 120