Java Program To Check Factorial of Number

Java Program to Find Factorial of a Number

In this program, we will learn to find the factorial of a number 

The factorial of a positive number n is given by:

factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n

Example 1: Using for loop

public class Factorial {

    public static void main(String[] args) {

        int num = 9;
        long factorial = 1;
        for(int i = 1; i <= num; ++i)
        {
            // factorial = factorial * i;
            factorial *= i;
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}

Output :

Factorial of 9 = 362880

In this program, we've used for loop to loop through all numbers between 1 and the given number num(10), and the product of each number till num  is stored in a variable factorial.

 

Example 2: Using while loop

public class Factorial {

    public static void main(String[] args) {

        int num = 9, i = 1;
        long factorial = 1;
        while(i <= num)
        {
            factorial *= i;
            i++;
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}

Output :

Factorial of 9 = 362880

In the above program, unlike a for loop, we have to increment the value of i inside the body of the loop.

Though both programs are technically correct, it is better to use for loop in this case. It's because the number of iteration (upto num) is known.