Program to print Factorial in java [Java interview]

Program to print Factorial in java.

This article will help you to understand “Java Program to Print Factorial.”

Factorials are just products, indicated by an exclamation mark. For instance, “five factorial” is written as “5!” and means 5*4*3*2*1 = 120. In general, n! (“enn factorial”) means the product of all the whole numbers from 1 to n.

Java Program to Print Factorial

package com.codenuclear;

import java.util.Scanner;

public class PrintFactorial {
	public static void main(String args[]) 
	{
		double fact = 1;
		System.out.println("Please Enter a number to calculate it's Factorial.");
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		scanner.close();
	
		if (n < 0) 
		{
			System.out.println("Please Enter Positive Number Only.");
		} 
		else 
		{
			for (int i = 1; i <= n; i++) 
			{
				fact = fact * i;
			}
			
			System.out.println("Factorial of :- " + n + " is :- " + fact);
		}
	}
}

Output Please Enter a number to calculate it’s Factorial. 5 Factorial of :- 5 is :- 120.0