Let’s see how to write a simple Java program to calculate the factorial
If you don’t know what is factorial, let me show you!!
Factorial is Multiplying given integer with the sequence of descending positive integers.
For example, The value of 5! is 120.
which is, 5 x 4 x 3 x 2 x 1 = 120
Let’s write a Factorial Program in Java now:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.util.Scanner; /** * * @author agur */ public class factorial { public static void main(String args[]){ int n, fact = 1; Scanner in = new Scanner(System.in); //get the limit first System.out.println("Enter the limit:"); n = in.nextInt(); System.out.println("Factorial is:"); for(int i=1; i<=n; i++){ //calculate the factorial fact = fact * i; //print the value System.out.println(fact); } } } |
The output of the above program will be:
1 2 3 4 5 6 7 8 |
Enter the limit: 5 Factorial is: 1 2 6 24 120 |