C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Recursion

C# Recursion

Recursion is a technique where a method calls itself to solve a smaller version of the same problem.

1 - Factorial

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

2 - Fibonacci

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

3 - Iterative vs Recursive

// 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;
}

Note: Every recursive method must have a base case that stops the recursion. Without it, the method calls itself infinitely and causes a StackOverflowException.

-Tip-