</>

Technology

Java Programs

Difficulty

Beginner

Interview Question

Write a Java program to find the factorial of a number using recursion and iteration.

Answer

Factorial of a Number in Java

Method 1: Iterative (Loop)

Java
public class FactorialIterative {
    public static void main(String[] args) {
        int n = 5;
        long factorial = 1;

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

        System.out.println("Factorial of " + n + " = " + factorial);
    }
}

Output

CODE
Factorial of 5 = 120

Step Trace for 5!

CODE
i=1: factorial = 1 × 1 = 1
i=2: factorial = 1 × 2 = 2
i=3: factorial = 2 × 3 = 6
i=4: factorial = 6 × 4 = 24
i=5: factorial = 24 × 5 = 120

Method 2: Recursive

Java
public class FactorialRecursive {

    public static long factorial(int n) {
        if (n == 0 || n == 1) return 1;   // base case
        return n * factorial(n - 1);       // recursive call
    }

    public static void main(String[] args) {
        for (int i = 0; i <= 10; i++) {
            System.out.println(i + "! = " + factorial(i));
        }
    }
}

Output

CODE
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800

Recursion Call Stack for factorial(4)

CODE
factorial(4)
  → 4 × factorial(3)
      → 3 × factorial(2)
          → 2 × factorial(1)
              → return 1      [base case]
          → 2 × 1 = 2
      → 3 × 2 = 6
  → 4 × 6 = 24

Using BigInteger for Large Factorials

Java
import java.math.BigInteger;

public static BigInteger bigFactorial(int n) {
    BigInteger result = BigInteger.ONE;
    for (int i = 2; i <= n; i++) {
        result = result.multiply(BigInteger.valueOf(i));
    }
    return result;
}

System.out.println("20! = " + bigFactorial(20));
// → 2432902008176640000

Follow AutomateQA