Java Program to Find Factorial of a Number

Factorial is one of the most important mathematical operations used in programming and algorithms.

It is commonly used in permutations, combinations, and recursion-based problems.

1. Understanding the Problem

Find the factorial of a given number.

5! = 5 × 4 × 3 × 2 × 1 = 120
3! = 6
0! = 1

2. Using For Loop

Java
Factorial using for loop
import java.util.Scanner;

public class FactorialForLoop {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        long fact = 1;

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

        System.out.println("Factorial = " + fact);
    }
}
Enter a number: 5
Factorial = 120

3. Using While Loop

Java
Factorial using while loop
import java.util.Scanner;

public class FactorialWhileLoop {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        long fact = 1;
        int i = 1;

        while (i <= num) {
            fact *= i;
            i++;
        }

        System.out.println("Factorial = " + fact);
    }
}

4. Using Recursion

Java
Factorial using recursion
import java.util.Scanner;

public class FactorialRecursion {

    static long factorial(int n) {
        if (n == 0 || n == 1)
            return 1;
        return n * factorial(n - 1);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        long result = factorial(num);

        System.out.println("Factorial = " + result);
    }
}

5. Common Mistakes

1. Not handling 0! correctly (it should be 1).

2. Using int instead of long for large numbers (overflow issue).

3. Infinite recursion due to missing base condition.

4. Not validating negative input.

6. Applications

1. Used in permutations and combinations.

2. Important in probability calculations.

3. Used in algorithm design and recursion problems.

Conclusion

Factorial calculation in Java can be done using loops or recursion.

Understanding factorial strengthens your knowledge of loops, recursion, and mathematical logic.