Home » Core Java » Factorial in java using for loop and recursion

Factorial in java using for loop and recursion

What is factorial?

Factorial of a number N is given as the product of all numbers from 1 till N. It is denoted by symbol !.
e.g.
factorial of 5 = 5! = 1*2*3*4*5 = 120
factorial of 6 = 6! = 1*2*3*4*5*6 = 720
factorial of 7 = 7! = 1*2*3*4*5*6*7 = 5040

Factorial in java can be found in the following ways:

1. Using for loop
2. Using Recursion

Method1 : factorial in java using for loop

The below demo program explains how to find factorial in java using for loop.

package com.mathapachi;
public class FactorialDemo {
	public static void main(String[] args) {
		int number = 6;
		System.out.println("Factorial of Number "+number +"="+fact(number));
		number = 12;
		System.out.println("Factorial of Number "+number +"="+fact(number));
		number = 11;
		System.out.println("Factorial of Number "+number +"="+fact(number));
		number=7;
		System.out.println("Factorial of Number "+number +"="+fact(number));
	}
	
	public static int fact(int number){
	      int product = 1;
	      for(int i=1;i<=number;i++){
		product *= i;
	      }
              return product;		
	}

}

The Output of the above program to find factorial in java using for loop is as below:

Factorial of Number 6=720
Factorial of Number 12=479001600
Factorial of Number 11=39916800
Factorial of Number 7=5040

Method2 : factorial in java using Recursion

Recursion is a logic where the method calls itself again and again till the base condition at which point it returns.

The below program explains as to how factorial can be calculated using recursion. The same above program has been converted into recursion logic as below:

package com.mathapachi;
public class FactorialDemo {
	public static void main(String[] args) {
		int number = 6;
		System.out.println("Factorial of Number "+number +"="+fact(number));
		number = 12;
		System.out.println("Factorial of Number "+number +"="+fact(number));
		number = 11;
		System.out.println("Factorial of Number "+number +"="+fact(number));
		number=7;
		System.out.println("Factorial of Number "+number +"="+fact(number));
	}
	
	public static int fact(int number){
	     if(number == 1){
		return number;
	     }
	     int product = number*fact(number-1);
             return product;		
	}

}

The output of the above program is as below which is same as in the previous method 1.

Factorial of Number 6=720
Factorial of Number 12=479001600
Factorial of Number 11=39916800
Factorial of Number 7=5040