In this article we will explain to you how to find the factorial of a number in java through Iteration as well as Recursion.
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.
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.
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:
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.
The output of the above program would be
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,
Given below is a program which calculates the factorial of 7 using recursion.