Hackerss.com

hackerss
hackerss

Posted on

Java Calculate factorial of a number using recursion


import java.util.Scanner;

public class Factorial {

   /**
   * This method calculates the factorial of a number.
   * @param number the number to calculate the factorial of.
   * @return int Obtains the factorial of the number.
   */   
   public int factorial(int number) {
       //Base case
       if (number == 0) {
           return 1;
       } else {
           //Recursive case
           return number * factorial(number - 1);
       }
   }

   /**
   * One Example
   */
   public static void main(String args[]) throws IOException {

      Factorial factorial = new Factorial();

      //Example
      int fact = factorial.factorial(5);

      //Output
      System.out.println("Factorial of 5 is :" + fact); //120

   }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)