Skip to content

Recursion

Recursion

Recursion is a method that calls itself. Every recursive method has two parts:

  1. Base case — where we stop and return a result directly.
  2. Recursive step — we reduce the problem to a smaller version of itself.

Example: factorial

static long Factorial(int n)
{
    if (n <= 1) return 1;        // base case
    return n * Factorial(n - 1); // recursive step
}

Factorial(4) → 4 * 3 * 2 * 1 = 24.

Example: Fibonacci numbers

static int Fib(int n)
{
    if (n < 2) return n;
    return Fib(n - 1) + Fib(n - 2);
}

This version is clear but slow: it recomputes the same values many times. Fix it with memoization or an iterative version.

The most common mistakes

  • Missing base case — leads to a StackOverflowException.
  • The recursive step doesn't move toward the base case.
  • int overflows for large factorials — use long.

Practice

Solve "Factorial" and "N-th Fibonacci number". Then rewrite Fibonacci with a loop and compare.