C# Recursion
Recursion
Recursion means that a method calls itself.
Why would a method call itself? Some problems contain a smaller copy of the same problem. For example, to count down from 5, you say "5", and then you count down from 4. To count down from 4, you say "4", and then you count down from 3, and so on.
A recursive method does one small step, and then calls itself to do the rest:
Example
static void Countdown(int number)
{
if (number > 0)
{
Console.WriteLine(number);
Countdown(number - 1);
}
}
static void Main(string[] args)
{
Countdown(5);
}
Example explained
Countdown(5) prints 5 and calls Countdown(4).
Countdown(4) prints 4 and calls Countdown(3), and so on.
At last, Countdown(0) does nothing, because 0 > 0 is false. Then the calls stop.
Halting Condition
Every recursive method needs a halting condition: a condition where the method stops calling itself.
In the example above, the method stops when number becomes 0. It works like the condition in a while loop.
Without a halting condition, the method calls itself forever:
Example
static void Countdown(int number)
{
Console.WriteLine(number);
Countdown(number - 1); // Never stops
}
Each method call uses a little memory. After many thousands of calls, there is no more memory for new calls, and the program crashes with a "stack overflow" error.
Sum of Numbers
A recursive method can also return a value. This method adds all numbers from 1 to 10:
Example
static int Sum(int number)
{
if (number > 0)
{
return number + Sum(number - 1);
}
else
{
return 0;
}
}
static void Main(string[] args)
{
int result = Sum(10);
Console.WriteLine(result);
}
Example explained
Sum(10) returns 10 + Sum(9).
Sum(9) returns 9 + Sum(8), and so on.
Sum(0) returns 0. This is the halting condition, so the calls stop.
Then all the numbers are added together: 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0, which is 55.
Factorial
The factorial of a number is the number multiplied by every whole number below it, down to 1. For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1, which is 120.
This is the same idea: the factorial of 5 is 5 times the factorial of 4:
Example
static int Factorial(int number)
{
if (number > 1)
{
return number * Factorial(number - 1);
}
else
{
return 1;
}
}
static void Main(string[] args)
{
Console.WriteLine(Factorial(5));
}
Here, the halting condition is when number is 1: Factorial(1) returns 1, and the calls stop.