Factorial Program Using Loop in Java
#Factorial Program Using Loop in Java
Factorial Program Using Loop in Java
Factorial is a mathematical operation where a number is multiplied by all its preceding positive integers. It is denoted by n! and is calculated as follows:
Examples:
In this article, we will discuss how to calculate the factorial of a number using loops and recursion in Java.
A loop-based approach iterates through all numbers up to the given number and multiplies them together to compute the factorial.
class FactorialExample {
public static void main(String args[]) {
int i, fact = 1;
int number = 5; // Number for factorial calculation
for (i = 1; i <= number; i++) {
fact = fact * i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
}
fact = 1
.fact
by the loop variable.fact
gives the factorial of the number.
A recursive approach solves the problem by calling the function repeatedly with a decremented value of n
until n = 1
.
public class FactorialRecursion {
public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive call
}
}
public static void main(String[] args) {
int number = 5;
System.out.println("Factorial of " + number + " is: " + factorial(number));
}
}
n-1
until it reaches n=1
.n
.Both methods are useful in different scenarios. Choose the best approach based on performance and readability.
If you found this article helpful, follow us for more updates on: 📌 Instagram | 📌 LinkedIn | 📌 Facebook | 📌 Twitter
This article is contributed by the Developer Indian Team. If you find any mistakes or have suggestions, feel free to share your feedback!