Recursion


Recursion is a general programming technique used to solve problems with a "divide and conquer" strategy.

Most computer programming languages support recursion by allowing a function or member function to call itself within the program text. For example:

int factorial(int n)
{
    if (n == 1)
        return 1;
    else
        return n * factorial(n - 1);   // Recursive function call
}

A recursive function call will always be conditional. There must be at least one base case for which the function produces a result trivially without a recursive call. For example:

int factorial(int n)
{
    if (n == 1)   // Base case - no recursion
        return 1;
    else
        return n * factorial(n - 1);
}

A function with no base cases leads to "infinite recursion" (similar to an infinite loop).

In addition to the base case(s), a recursive function will have one or more recursive cases. The job of a recursive case can be seen as breaking down complex inputs into simpler ones. In a properly designed recursive function, with each recursive call, the input problem must be simplified in such a way that eventually the base case must be reached. For example:

int factorial(int n)
{
    if (n == 1)
        return 1;
    else
        return n * factorial(n - 1);   // n - 1 gets us closer to 1
}

Recursion requires automatic storage - each new call to the function creates its own copies of the local variables and function parameters on the program stack.

Recursion is never a required programming technique. Recursion can always be replaced by either

  1. a loop, or
  2. a loop and a stack (that takes the place of the program call stack used by recursion)

In the first case, a non-recursive algorithm will usually be superior, if only in terms of memory usage. But in the second case, we might choose a recursive algorithm if it is shorter or easier to code (which is often true).