When a method calls itself continuously, that process is called recursion. If we want to give an example of recursion, one example that comes to mind is factorial. What is factorial? Factorial is the process of obtaining a specific value by multiplying each number from 1 to a given number.
For example factorial of 5 is : 1 * 2 * 3 * 4 * 5 = 120. Now the problem is how to find factorial value in program. We can do this using factorial. First, see the example, and then we will understand how the program will work.
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
in this example, assume that the value of n is 5.
The first time the factorial method will have the value 5 on n, check if the value is equal to zero or not. This condition is the base condition if the condition reaches the program then the recursion will end. The value of n is 5 thats why the function will execute the else block.
The first time the method calls with a value 5 of n, then the second time with the value 4, then 3, then 2, then 1, and the last call with the value 0 of n. And the base condition will be true. Then
The last or 6th call of the method will return the value 1.
5th, where the value of n is 1 and the previous call of the method return 1, multiply them by 1 * 1 = 1 and this call of the method will return 1
4th, where the value of n is 2 and the previous call of the method return 1, multiply them by 2 * 1 = 2 and this call of the method will return 2
3rd, where the value of n is 3 and the previous call of the method return 2, multiply them by 3 * 2 = 6 and this call of the method will return 6
2nd, where the value of n is 4 and the previous call of the method return 6, multiply them by 4 * 6 = 24 and this call of the method will return 24
1st, where the value of n is 5 and the previous call of the method return 24, multiply them by 5 * 24 = 120 and this call of the method will return 120
and the program will end.
The recursion process is a bit difficult to understand. You need more and more practice to master the recursion.