In this article we will explain to you how to find the factorial of a number in java through Iteration as well as Recursion.

- Finding factorial of a number using Iteration in Java
Let the number whose factorial is to be found is stored in the variable 'n'. A new variable 'factorial' of type integer is declared and initialised with the value 1.

int factorial = 1;
Now, next thing is to multiply the variable 'factorial' with all natural numbers from 1 to n. For this purpose, we use a for loop with a counter variable i that ranges from 1 to n. Within the loop, the existing value of factorial will be multiplied with the loop counter.

for (int i = 1; i <= n; i++) {
factorial = factorial * i;
}
Let us take a small number n = 3 to understand how the loop works. Before starting the loop, factorial would be initialised to one. The loop will then execute thrice with the value of i = 1, 2 and 3. When the value of i becomes 4, the loop condition fails and program exits the loop. When the value of i is 1, the existing factorial would be multiplied with 1 which again gives one. In the second iteration, factorial will be multiplied with 2 and in the third iteration with 3. These calculations are shown below:

factorial = 1
i = 1 factorial = factorial * i = 1 * 1 = 1
i = 2 factorial = factorial * i = 1 * 2 = 2
i = 3 factorial = factorial * i = 2 * 3 = 6
When the loop exists, the value factorial which was initially one would be already multiplied by all natural numbers from 1 to n. Thus, factorial holds the factorial of the number.

Given below is a program which finds the factorial of the number 7.

public class FactorialNumber {
public static void main(String[] args) {
int n = 7;
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial = factorial * i;
}
System.out.println("The factorial of 7 is " + factorial);
}
}
The output of the above program would be

The factorial of 7 is 5040
- Finding factorial of a number using Recursion in Java
The factorial of a number can be found using recursion also. The base case that can be taken is the factorial of the number 0 or 1, both of which are 1. The factorial of other number n is that number multiplied by the factorial of (n-1). Mathematically,

factorial ( 0 ) = 1
factorial ( n ) = n * factorial ( n - 1 )
Given below is a program which calculates the factorial of 7 using recursion.

public class FactorialNumber {
public static void main(String[] args) {
int n = 7;
int result = factorial(n);
System.out.println("The factorial of "+ n +" is " + result);
}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}