Factorial

A factorial is a product of an integer and all the integers below it. In other words, factorial (!) Is the product of all integers from 1 to n.

For example:

If N = 5, then 5! is 5 x 4 x 3 x 2 x 1 = 120

Logic

First of all, we declare one temporary variable fact with value 1, now we are going to use this variable to store factorial.

After taking input from the user, we need to start one loop from 1 to N, and inside the loop, we multiply current number “i” with variable fact and then store the result again in fact variable until the loop terminates. Once the loop is over we have to print the fact variable containing factorial of a given number (N).

Program

import java.util.Scanner;

public class Factorial {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int fact = 1;

        // Take numbers from user
        System.out.print("Enter any number : ");
        int num = scanner.nextInt();

        for(int i = 1; i <= num; i++) {
            fact = fact * i;
        }

        System.out.println("\nFactorial of " + num + " : " + fact);
    }

}

Output

Enter any number : 5
Factorial of 5 : 120