Calculate Factorial using Recursion in Java

Recursion means a method calling directly or indirectly themselves. Recursion is a useful programming technique. In some cases, it enables you to develop a straightforward and simple solution to an otherwise difficult problem. This post introduces you how to compute the factorial of any input number.

The factorial of a number n can be recursively defined as follows:

0! = 1;
n! = n × (n – 1) × ... × 2 × 1 = n × (n - 1)!; n > 0

Lets calculate the above factorial using java code example:

import java.util.Scanner;

public class CalculateFactorial {

       public static void main(String[] args) {

              Scanner input = new Scanner(System.in);
              System.out.print("Enter any positive integer: ");
              int n = input.nextInt();

              System.out.println("Factorial of " + n + " is " + factorial(n));
       }

       /** Return the factorial for a specified number */
       public static long factorial(int n) {
              if (n == 0) {
                     // Base case
                     return 1;
              }

              else {
                     // Recursive call
                     return n * factorial(n - 1);
              }

       }
}



The output of above code Listing would look like:

   Enter any positive integer: 3
   Factorial of 3 is 6

No comments:

Post a Comment