Factorial of a Number in Java

In this post, you will learn how to find out the factorial of a number in Java.

Factorial :

Factorial of a number is the multiplication of all smaller integers than the number, 
including the number itself.

We can write factorial of a number as,

Solution :

There are mainly two ways to write the factorial program in Java:

  1. Factorial using loop.
  2. Factorial using recursion.

Approach 1 : Factorial using Loop

public class B{
    public static void main(String[] args) {
        int number = 5; // Replace with the desired number

        int fact = 1;
        for (int i = 1; i <= number; i++) {
            fact *=i;
        }

        System.out.println("The factorial of " + number + " is: " + fact);
    }
}

Output :

The factorial of 5 is: 120

Approach 2 : Factorial using Recursion

public class FactorialCalculator {
    public static void main(String[] args) {
        int number = 5; // Replace with the desired number

        int factorial = calculateFactorial(number);

        System.out.println("The factorial of " + number + " is: " + factorial);
    }

    public static int calculateFactorial(int n) {
        if (n == 0) {
            return 1;
        } else {
            return n * calculateFactorial(n - 1);
        }
    }
}

Output :

The factorial of 5 is: 120

More basic Java Programs:

Java Program to Print Multiplication Table of a Number

Java program to Count the Total number of Characters in a String

Java Program to Display Fibonacci Series

Prime Number Program in Java

 

Leave a Comment

%d bloggers like this:
Python4U
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.