Factorial Program in Java

 Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n!. For example:

4! = 4*3*2*1 = 24  
5! = 5*4*3*2*1 = 120

Factorial Program using while loop

public class FactorialProgram {

  public static void main(String[] args) {

    int factNumber = 4;
    int total = 1;
    int n = 1;
    while (n <= factNumber) {
      total = total * n;
      n = n + 1;
    }
    System.out.println("Factorial of " + factNumber + " is " + total);
  }
}

Output

Factorial of 4 is 24

Factorial Program using For loop

public class FactorialProgram {

  public static void main(String[] args) {

    int factNumber = 5;
    int total = 1;

    for (int n = 1; n <= factNumber; n++) {
      total = total * n;
    }
    System.out.println("Factorial of " + factNumber + " is " + total);
  }
}

Output

Factorial of 5 is 120

Factorial Program using recursion

class FactorialProgram {
  public static int factorial(int n) {
    if (n == 0) {
      return 1;
    } else {
      return (n * factorial(n - 1));
    }
  }

  public static void main(String args[]) {
    int total = 1;
    int factNumber = 5;
    total = factorial(factNumber);
    System.out.println("Factorial of " + factNumber + " is " + total);
  }
}

Output

Factorial of 5 is 120