Print Factorial of a Given Number in Java



Given a number of type integer, write a Java program to print its factorial. The factorial of a positive integer n is the product of all values from n to 1. For example, the factorial of 3 is (3 * 2 * 1 = 6).

Let's understand the problem statement with examples ?

Example Scenario 1:

Input: int n = 4;
Output: res = 24 

Calculation: 4! = 4 * 3 * 2 * 1 = 24

Example Scenario 2:

Input: int n = 0;
Output: res = 1

Factorial of 0 is always 1.

Finding Factorial using Iteration

In the iterative approach, we use a loop like for or while to multiply the numbers in descending order to get the factorial.

Example

In this Java program, we find factorial of a number using a for loop.

public class Example {
    public static void main(String[] args) {
        int num = 6;
		// initial factorial
        int fact = 1; 
        System.out.println("The given number is: " + num);
        // loop to calculate factorial
        for(int i = num; i >= 2; i--) {
            fact = fact * i;
        }
        // printing the result
        System.out.println("The factorial of " + num + " is: " + fact);
    }
}

On running the above code, it will show the following output ?

The given number is: 6
The factorial of 6 is: 720

Finding Factorial using Recursion

Recursion is a programming practice that allows a method to call itself as long as necessary. The method that calls itself is called as recursive method. While working with recursion it is necessary to provide a base case that forces the recursive method to return the result or terminate the method calling.

Example

The following Java program demonstrates how to find factorial using recursion in Java. Here, the method will be called recursively to calculate factorial as long as the given input is greater than or equal to 1.

public class Example {
   // recursive method to calculate factorial
   public static int factorialCalc(int myInput) {
      // checking if given number is greater than 1 or not
      if (myInput >= 1) {
         // finding the factorial
         return myInput * factorialCalc(myInput - 1);
      } else {
         return 1;
      }
   }
   public static void main(String[] args) {
      int myInput = 7;
      System.out.println("The given number is: " + myInput);
      // calling method to calculate factorial 
      int results = factorialCalc(myInput);
      // printing the result
      System.out.println("The factorial of " + myInput + " is " + results);
   }
}  

When you execute the above code, it will display the following output ?

The given number is: 7
The factorial of 7 is 5040
Updated on: 2024-09-13T15:55:01+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements