Factorial program in java

Let’s learn factorial program in java.

Factorial program in java

Factorial is the product of all integers 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)

factorial program in java

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 learn to find factorial program 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 program using while loop

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 program using do while loop

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