Java Factorial

Hey guys!! Welcome to flower brackets blog. Let’s write program using recursion. I would like to give a demo on java factorial.

Factorial

Usually the term factorial is used in permutation and combination. The term factorial is the multiplication of non-negative descending numbers.

Also Read – Factorial Program in Java

Factorial example

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

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

Java Factorial

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class FactorialUsingRecursion
{
   public static void main(String[] args) throws NumberFormatException, IOException
   {
      System.out.println("Please enter number to calculate its factorial:");

      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      int x = Integer.parseInt(br.readLine());

      // Here we call the recursive function to generate factorial
      int result = factorial(x);

      System.out.println("Factorial of " + x + " is = " + result);
   }

   static int factorial(int y)
   {
      if(y <= 1)
         return 1;
      else
         return y * factorial(y - 1);
   }
}

Output :

java factorial

You May Also Like