Factorial program in java

In this post we are going to learn factorial program in java.

factorial program in java

Factorial is nothing but the product of all numbers less than or equal to given number. Denoted as n! For example,

6! = 6 * 5 * 4 * 3 * 2 * 1 = 720 (6! means 6 factorial)

4! = 4 * 3 * 2 * 1 = 24 (4! means 4 factorial)

Let’s see factorial program in java using for loop,

public class FactorialDemo
{
   public static void main(String[] args)
   {
      int number = 6, factorial = 1; 
      for(int a = 1; a <= number; a++)
      {
         factorial = factorial * a;
      }
      System.out.println("Factorial of " + number + " is : " + factorial);
   }
}

Output:

Factorial of 6 is : 720


Using recursion

public class FactorialRecursion
{
   public static void main(String[] args)
   {
      int factorial = 1; 
      int number = 6; 
      factorial = factorialFunction(number); 
      System.out.println("Factorial of " + number + " is : " + factorial);
   }

   static int factorialFunction(int num)
   {
      if(num == 0)
      {
         return 1;
      }
      else
      {
         return(num * factorialFunction(num - 1));
      }
   }
}

Output:

Factorial of 6 is : 720


Using while loop

Also read – sum and average of values in an array in java

import java.util.Scanner;

public class FactorialWhile
{
   public static void main(String[] args)
   {
      int number, factorial = 1; 
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a number : "); 
      number = sc.nextInt();
 
      int a = 1;
      while(a <= number)
      {
         factorial = factorial * a;
         a++;
      }
      System.out.println("Factorial of " + number + " is : " + factorial);
      sc.close();
   }
}

Output:

Please enter a number : 5
Factorial of 6 is : 120


Using do while loop

import java.util.Scanner;

public class FactorialDoWhile
{
   public static void main(String[] args)
   {
      int number, factorial = 1; 
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a number : "); 
      number = sc.nextInt();
 
      int a = 1; 
      do
      {
         factorial = factorial * a;
         a++;
      }
      while(a <= number); 
      System.out.println("Factorial of " + number + " is : " + factorial);
      sc.close(); 
   }
}

Output:

Please enter a number : 7
Factorial of 7 is : 5040