Java Program to find factorial of a number


In this program, You will learn how to find factorial of a number in java.


3! = 1 * 2 * 3

4! = 1 * 2 * 3 * 4

Example: How to find factorial of a number in java.

import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int n, i;
        long f = 1;

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number:");
        n = sc.nextInt();

        for (i = 1; i <= n; i++) {
            f = f * i;
        }

        System.out.println("Factorial is:" + f);
    }
}

Output:

Enter a number:4
Factorial is:24