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:
- Factorial using loop.
- 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