Factorial Program in Java

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:

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:

Enter the limit:
5
Factorial is:
1
2
6
24
120

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top