Write Java program to Find Factorial of a Number


This Java program calculates the factorial of a given integer number entered by the user. The program uses a for loop to iterate through all the numbers from the input integer down to 1, multiplying each number together to get the factorial.

  • The program starts by creating a Scanner object to read input from the user. It then prompts the user to enter an integer number, which is stored in the integer variable num.
  • The program then uses a for loop to calculate the factorial of the input number. The loop starts at num and decrements by 1 each iteration until it reaches 1. Inside the loop, the variable fact is multiplied by the loop variable i. This means that fact is multiplied by every number from num down to 1.
  • After the loop completes, the program prints out the factorial of the input number using System.out.println(). The output includes both the input number and its factorial.

Overall, this program is a straightforward way to calculate the factorial of an integer in Java using a for loop. However, it is worth noting that the factorial of large numbers can become very large and may overflow the limits of the long data type. In such cases, it may be necessary to use a different approach, such as using the BigInteger class in Java.

Source Code

import java.util.*;
public class Factorial_Number
{
	public static void main(String args[])
	{
		int num;
		long fact;
 
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the Integer Number : ");
		num = input.nextInt();
 
		//find factorial
		fact = 1;
		for (int i = num; i >= 1; i--)
		{
			fact *= i;
		}
 
		System.out.println(num+" Factorial is : " + fact);
	}
}

Output

Enter the Integer Number : 6
6 Factorial is : 720

Example Programs