Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 8: Write a Java program to calculate the factorial of a number.

Factorial.java

import java.util.Scanner;

public class Factorial
{
	public static void main(String[] args)
	{
		int n;
		int fact=1;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter the number");
		n=sc.nextInt();
		
		if(n == 0 || n == 1)
		{
			System.out.println("Factorial: "+fact);
		}
		else
		{
			for(int i=1;i<=n;i++)
			{
				fact=fact*i;
			}
			System.out.println("Factorial: "+fact);
		}
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.