Recursion
A method that calls itself: base cases, recursive cases, how the call stack handles it, and when to use a loop instead.
The two parts of every recursive method
Base case: a simple input answered directly, without calling itself. This is what stops the recursion. Recursive case: the method calls itself with a smaller input that moves toward the base case.
5! = 5 × 4 × 3 × 2 × 1, which is the same as 5 × 4!. So n! = n × (n-1)!, and 1! = 1 is the base case.
More examples
// Sum of digits: 4096 → 4 + 0 + 9 + 6 = 19static int SumDigits(int n){ if (n < 10) return n; // base case: one digit return n % 10 + SumDigits(n / 10); // last digit + sum of the rest} Console.WriteLine(SumDigits(4096));19
// x to the power of n, halving n each time (fast!)static double Power(double x, int n){ if (n == 0) return 1; double half = Power(x, n / 2); return n % 2 == 0 ? half * half : half * half * x;} Console.WriteLine(Power(2, 10));1024
When recursion goes wrong
static int Broken(int n){ return n * Broken(n - 1); // no base case!}// Broken(5) → Broken(4) → … → Broken(-10000) → …// Process terminated: Stack overflow.Beware of repeated work
// Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13 …static long FibSlow(int n) => n < 2 ? n : FibSlow(n - 1) + FibSlow(n - 2); static long FibFast(int n){ long a = 0, b = 1; for (int i = 0; i < n; i++) { (a, b) = (b, a + b); } return a;} Console.WriteLine(FibFast(50)); // instant// FibSlow(50) makes billions of calls: it takes minutes.12586269025
FibSlow calls itself twice per level, so it recomputes the same values again and again. The loop version computes each value once. Later, in the DSA course, you will learn memoization, which fixes this while keeping the recursive style.
Recursion or a loop?
| Use recursion when… | Use a loop when… |
|---|---|
// A natural fit: total size of a folder and all its sub-foldersstatic long FolderSize(DirectoryInfo dir){ long size = 0; foreach (FileInfo f in dir.GetFiles()) size += f.Length; foreach (DirectoryInfo sub in dir.GetDirectories()) size += FolderSize(sub); // the same problem, one level down return size;}static string Reverse(string s) that returns the string reversed (e.g. "steel" → "leets").
Show a hint
Show the solution
static string Reverse(string s){ if (s.Length <= 1) return s; return s[^1] + Reverse(s[..^1]); // last char + reverse of the rest} Console.WriteLine(Reverse("steel"));leets
Remember
A recursive method calls itself on a smaller input. Always have a base case, and make every call move toward it. Each pending call is a stack frame; too deep means StackOverflowException. Prefer recursion for nested/tree data; prefer loops for simple repetition.