Factorial program in java

Let’s learn factorial program in java.

Factorial program in java

factorial of a number in java or factorial in java is one of the common java interview question.

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

factorial program in java

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

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

Below are few ways to execute factorial program.

  1. factorial program using for loop.
  2. factorial program using recursion.
  3. factorial program using while loop.
  4. factorial program using do-while loop.

Now let’s see java program to find factorial of a number using for loop. Here’s the java program.

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


Factorial using recursion in java

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


Factorial using while loop in java

import java.util.Scanner;
public class FactorialUsingWhileLoop
{
   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


Factorial using do while loop in java

import java.util.Scanner;
public class FactorialDoWhileLoop
{
   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