Java program to print factorial of given number

Views: 140   

Following program shows you how to print factorial of given number.
In this program we get input from user and prints factorial of that number using for loop

import java.util.Scanner;

public class BasicMath18 {

    public static void main(String[] args) {

        System.out.println("Please enter a number:");

        Scanner in = new Scanner(System.in);
        int input = in.nextInt();

        int result = 1;

        for (int i = 1; i <= input; i++) {
            result = result * i;

        }

        System.out.println(input + " factorial is: " + result);
    }

}

Output:

Please enter a number:
5
5 factorial is: 120
On By