Recursion vs iterative functions

A typical structure for a recursive function is as follows:

return_type function_name(parameter list)
{
   if (completion condition) {
      computation to get the answer directly
   } else {
      computation plus recursive call
   }
   return value;
}
If the function has no "completion condition" then essentially it will be stuck in an infinite sequence of recursive calls: sooner or later you must compute an answer without needing to make yet another function call.

Generally speaking, the recursive call is made on a smaller, or simpler version of the problem.

For example, suppose we want to calculate factorials: N! = 1*2*3*...*N

This leads to the following code:
int factorial(int N)
{
    int result;

    if (N <= 2) {
       result = N;
    } else {
       result = factorial(N-1) * N;
    }
    return result;
}
Note that we have a quitting condition - for the cases where it is simple to calculate the result without making a recursive call - and a recursive call (plus a little extra computation) to calculate the more "difficult" cases.

When we make a call like x = factorial(5);
what sequence of calls occurs?

factorial(5)
    factorial(4)
        factorial(3)
            factorial(2)

at this point the values are passed "back up the line"

 - i.e. factorial(2) returns 2
             then factorial(3) returns 6
                  then factorial(4) returns 24
                       then factorial(5) returns 120

Recursion: advantages and disadvantages


Other recursion examples