Recursion is a technique where a method calls itself to solve a smaller version of the same problem.
public static long Factorial(int n)
{
if (n <= 1) return 1; // base case
return n * Factorial(n - 1); // recursive call
}
Console.WriteLine(Factorial(5)); // 120
Console.WriteLine(Factorial(10)); // 3628800
public static int Fibonacci(int n)
{
if (n <= 1) return n;
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
for (int i = 0; i <= 10; i++)
Console.Write(Fibonacci(i) + " ");
// 0 1 1 2 3 5 8 13 21 34 55
// Recursive (elegant but slower for large n)
public static int SumRecursive(int n) =>
n <= 0 ? 0 : n + SumRecursive(n - 1);
// Iterative (preferred for performance)
public static int SumIterative(int n)
{
int total = 0;
for (int i = 1; i <= n; i++) total += i;
return total;
}