Factorial Program in Java

The program simply prints factorial of a given number.  A factorial is calculated by multiplying  all the numbers starting from 1 to all the way nth number. For example, factorial of 5 would be, 1 X 2 X 3 X 4 X 5, which is 120.

Screenshot from 2022 08 14 15 58 07

The same logic will be used in this article to calculate the same. However, there are various approaches to achieve this functionality.

Below are some approaches to calculate factorial of a number :

  1. Using Loop
  2. Using recursion
  3. Using ternary operator
  4. Using Java 8 reduce method

Example 1. Java program to calculate factorial of a number using Loop

In this example, we have simply used “for loop” and on each iteration, we’re incrementing the counter by 1 until it reaches to nth number.  Within the looping body, we’re multiplying the counter with the factorial variable which is having an initial value of 1, and storing the result in factorial variable itself. 

Program :

import java.util.Scanner;
public class FactorialProgram {
    public static void main(String[] args) {
        int number;
        int factorial = 1;
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter a number :: ");
        number = input.nextInt();
        for (int i = 1 ; i <= number; i++){
            factorial = factorial * i;
        }
        System.out.println("Factorial of "+number+" is :: "+ factorial);
    }
}

Output:

Please enter a number :: 5
Factorial of 5 is :: 120

Example 2. Java program to calculate factorial of a number using Recursion

Recursion function refers to a method which calls itself and terminates when some condition is triggered. Below is the example to calculate the factorial with the help of recursion function

Program:

public class FactorialProgram {
    static long getFactorial(int number) {
        if (number == 1) {
            return 1;
        } else {
            return number * getFactorial(number - 1);
        }
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int number;
        long factorial;
        System.out.print("Please enter a number :- ");
        number = input.nextInt();
        factorial = getFactorial(number);
        System.out.println("Factorial of " + number + " = " + factorial);
    }
}

Output:

Leave a Reply