In this example, we will calculate the factorial of a number taking the value from the user. You may also learn to find Factorial of a Number in Java Using recursion.
Before we begin, you should have the knowledge of the following:
Factorial of n number: Factorial of n number is the product of all the positive descending integers and is denoted by n!.
Example:
factorial of n (n!) = n * (n-1) * (n-2) * (n-3)….1
factorial of 5 (n!) = 5 * 4 * 3 * 2 * 1
NOTE: Factorial of 0 (0!) = 1
Java Program to Find a Factorial of a Number Using for loop.
//find the factorial of a number in java
import java.util.Scanner;
public class FactorialOfANumber
{
public static void main(String args[])
{
int fact=1;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = scanner.nextInt();
for(int i=1;i<=num;i++)
{
fact = fact * i;
}
System.out.println("Factorial of entered number is: "+fact);
}
}
Output:
Enter the number: 5
Factorial of entered number is: 120