Write a Java program to calculate the factorial of a given number.
What is a Factorial?
The factorial of a number nnn is the product of all positive integers from 1 to nnn.
It is denoted as n!n!n!.
For example:
- 5!=5×4×3×2×1=120
- 0!=10! = 10!=1 (by definition)
class Main {
public static void main(String[] args) {
int userNo = 5; // The number for which to calculate the factorial
long fact = 1; // Start with 1 because factorial of 0 and 1 is 1
// Loop to calculate the factorial
for (int i = 1; i <= userNo; i++) {
fact *= i; // Multiply fact by each number from 1 to userNo
}
// Print the result
System.out.println(fact); // Print the factorial value
}
}
Input Initialization:
userNo = 5: The number for which the factorial is calculated.
fact = 1: A long variable to store the factorial result (initialized to 1 because the factorial of 0 and 1 is 1).
Loop to Compute Factorial:
A for loop iterates from i = 1 to i = userNo (inclusive).
Inside the loop, fact is updated by multiplying it with i. This step accumulates the product of all integers from 1 to userNo.
Iteration Breakdown (for userNo = 5):
Iteration 1 (i = 1): fact = 1 × 1 = 1
Iteration 2 (i = 2): fact = 1 × 2 = 2
Iteration 3 (i = 3): fact = 2 × 3 = 6
Iteration 4 (i = 4): fact = 6 × 4 = 24
Iteration 5 (i = 5): fact = 24 × 5 = 120
Output the Result:
After the loop ends, fact contains the factorial of userNo.
The program prints the value of fact using System.out.println().
Output
For userNo = 5, the output is:
120