C# Recursion
Recursion is when a method calls itself. It is a natural way to solve problems that can be broken into smaller copies of the same problem: computing factorials, walking folder trees, searching sorted data, or exploring every path in a maze.
The two essential parts
Every recursive method needs:
- A base case — a simple input whose answer is known directly, which stops the recursion.
- A recursive case — the method calls itself with a smaller input, moving toward the base case.
using System;
class Program
{
static int SumTo(int n)
{
if (n == 0) // base case
return 0;
return n + SumTo(n - 1); // recursive case
}
static void Main()
{
Console.WriteLine(SumTo(5));
Console.WriteLine(SumTo(100));
}
}15
5050
SumTo(5) asks for 5 + SumTo(4), which needs 4 + SumTo(3), and so on down to SumTo(0), which returns 0. Then the pending additions complete in reverse order: 0 → 1 → 3 → 6 → 10 → 15.
Watching the calls
Printing with indentation makes the "going down" and "coming back up" visible:
using System;
class Program
{
static long Factorial(int n, int depth = 0)
{
string indent = new string(' ', depth * 2);
Console.WriteLine(quot;{indent}Factorial({n})");
if (n <= 1)
return 1;
long result = n * Factorial(n - 1, depth + 1);
Console.WriteLine(quot;{indent}= {result}");
return result;
}
static void Main()
{
Factorial(4);
}
}Factorial(4)
Factorial(3)
Factorial(2)
Factorial(1)
= 2
= 6
= 24
Each call gets its own copy of n and indent on the call stack. When a call returns, its frame is removed and the caller continues where it left off.
Classic examples
using System;
class Program
{
// Greatest common divisor (Euclid's algorithm)
static int Gcd(int a, int b) => b == 0 ? a : Gcd(b, a % b);
// Power by repeated squaring: far fewer calls than multiplying n times
static long Power(long x, int n)
{
if (n == 0) return 1;
long half = Power(x, n / 2);
return n % 2 == 0 ? half * half : half * half * x;
}
// Reverse a string
static string Reverse(string s) => s.Length <= 1 ? s : Reverse(s[1..]) + s[0];
// Binary search in a sorted array
static int Find(int[] arr, int target, int lo, int hi)
{
if (lo > hi) return -1;
int mid = (lo + hi) / 2;
if (arr[mid] == target) return mid;
return arr[mid] < target ? Find(arr, target, mid + 1, hi) : Find(arr, target, lo, mid - 1);
}
static void Main()
{
Console.WriteLine(Gcd(48, 180));
Console.WriteLine(Power(2, 40));
Console.WriteLine(Reverse("recursion"));
int[] sorted = { 2, 5, 8, 12, 16, 23, 38, 56, 72, 91 };
Console.WriteLine(Find(sorted, 23, 0, sorted.Length - 1));
Console.WriteLine(Find(sorted, 7, 0, sorted.Length - 1));
}
}12
1099511627776
noisrucer
5
-1
Pitfalls: missing base cases and repeated work
If the base case is missing or never reached, the method calls itself until the call stack runs out and the process crashes with a StackOverflowException, which cannot be caught:
static int Broken(int n) => n + Broken(n - 1); // no base case: stack overflowNaive recursion can also be very slow when it solves the same sub-problem many times. The textbook Fibonacci definition Fib(n) = Fib(n-1) + Fib(n-2) makes an exponential number of calls. Caching results (memoization) or a simple loop fixes it:
using System;
using System.Collections.Generic;
class Program
{
static int calls = 0;
static long SlowFib(int n)
{
calls++;
return n < 2 ? n : SlowFib(n - 1) + SlowFib(n - 2);
}
static readonly Dictionary<int, long> cache = new();
static long FastFib(int n)
{
if (n < 2) return n;
if (cache.TryGetValue(n, out long known)) return known;
long value = FastFib(n - 1) + FastFib(n - 2);
cache[n] = value;
return value;
}
static void Main()
{
Console.WriteLine(quot;SlowFib(25) = {SlowFib(25)} using {calls} calls");
Console.WriteLine(quot;FastFib(80) = {FastFib(80)}");
}
}SlowFib(25) = 75025 using 242785 calls
FastFib(80) = 23416728348467685
Recursion or loops?
| Recursion is a good fit | A loop is a better fit |
|---|---|
| Tree-shaped data (folders, menus, expressions) | Simple counting or accumulating |
| Divide-and-conquer (merge sort, binary search) | Very deep repetition (millions of steps) |
| The problem is defined recursively | Performance-critical inner loops |
Test yourself
What is the purpose of the base case?
- To speed up the method
- To stop the recursion
- To call the method again
- To catch exceptions
What does F(3) return? static int F(int n) => n == 0 ? 1 : 2 * F(n - 1);
- 6
- 8
- 3
- 9
What happens when a recursive method never reaches its base case?
- It returns 0
- It loops forever silently
- A StackOverflowException crashes the process
- The compiler refuses to compile it