Recursion can be defined as:
A method that calls itself until a specific condition is met.
An excellent and simple example of recursion is a method that will get the factorial of a given number:
public int Factorial(int number)
{
return number == 0 ? 1 : n * Factorial(number - 1);
}
In this method, we can see that the method will take an argument, number
.
Step by step:
Given the example, executing Factorial(4)
number (4) == 1
?4 * Factorial(number-1)
(3)Factorial(3)
as the new argument.Factorial(1)
is executed and number (1) == 1
returns 1.4 * 3 * 2 * 1
and finally returns 24.The key to understanding recursion is that the method calls a new instance of itself. After returning, the execution of the calling instance continues.