Factorial of a number in Java - Coders PlayGround

Learn to code and change the future!

Saturday, 19 August 2017

Factorial of a number in Java

Hello everyone,

The factorial is denoted by "!"

So when we say, find 3 factorial, it is mathematically written as 3!

Now let us look into the formula as to how to find the factorial of any number.
Factorial of a number n is given by n! = n(n-1)(n-2)!

Suppose, factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.

The two important facts you should know about factorial: 
  • The factorial of 1! = 1
  • The factorial of 0! = 1

Now let us write to program to find the find the factorial of a given number.

import java.util.Scanner;
public class Factorial
{
 public static void main(String args[])
 {
  int i, fact=1;
  System.out.println("Enter the Number:");
  Scanner in= new Scanner(System.in);
  int a=in.nextInt();
  for(i=1;i<=a;i++)
  {
   fact=fact*i;
  }
  System.out.println(factorial +"!="+fact);
 }
}
OUTPUT
Enter the Number:
5
Factorial != 120


PropellerAds