Recursion in plain English
suggest changeRecursion 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)
- Is
number (4) == 1
? - No? return
4 * Factorial(number-1)
(3) - Because the method is called once again, it now repeats the first step using
Factorial(3)
as the new argument. - This continues until
Factorial(1)
is executed andnumber (1) == 1
returns 1. - Overall, the calculation “builds up”
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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents