Disclosure: When you purchase a service or a product through our links, we sometimes earn a commission.
Simple Java program to find Factorial of a number
January 17, 2018
The Java code below shows how to get the factorial of numbers. For instance 4! = 4 x 3 x 2 x 1 = 24.
Since Zero factorial is defined to be one, i.e. 0! = 1, the loop starts from 1.
The code below calculates the factorial of numbers from 1 to 10.
public class DisplayFactorial{
public static void main(String[] args){
int j = 1;
System.out.println("0! = " + 1);
for(int i=1; i<10; i++){
j = j *i;
System.out.println(i + "! = " + j);
}
}
}
When we run the program we will get output similar to the following:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800