*Recursion* occurs when a routine calls itself. Recursion can be a confusing topic because people don’t normally think recursively, but some problems are naturally recursive, and in those cases, it can be useful to design routines that match the problem’s recursive structure.

For example, earlier in this chapter, I defined the factorial of the number *N*, written as *N!* and given by 1 * 2 * 3 * … * *N*. You can also define the factorial function recursively as *N!* = *N* * (*N* – 1)!. The following C# code shows a recursive implementation of this function:

// Calculate n! recursively. public long Factorial(long n) { if (n <= 1) return 1; return n * Factorial(n - 1); }

If the parameter is 1 or less, the function simply returns 1. (The value 0! is 1 by ...

Start Free Trial

No credit card required