Java program to find factorial of a number
https:/gi.www/iftidea.com
Here's a Java program to find the factorial of a number using iteration:
public class Main { public static void main(String[] args) { int number = 5; long factorial = 1; for (int i = 1; i <= number; i++) { factorial *= i; } System.out.println("Factorial of " + number + " is " + factorial); } }
In this program, we first initialize an int
variable number
with the value 5
.
We then initialize a long
variable factorial
with the value 1
. We use a for
loop to iterate over the numbers from 1
to number
. For each iteration, we multiply factorial
by the current number.
The output of this program will be:
Factorial of 5 is 120
You can replace 5
with any other integer value to calculate its factorial. Note that the factorial of a negative number is undefined, and the factorial of a non-negative number that is greater than 20 may exceed the maximum value that can be stored in a long
variable.