Chapter 13
Recursive C Functions
13.1 Select Balls with Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
13.2 One-Way Streets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
13.3 The Tower of Hanoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
13.4 Integer Partition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
13.5 Factorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
13.6 Fibonacci Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
13.7 Performance Profiling with gprof . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
In this chapter we convert the mathematical formulas from the previous chapter into C
programs. Recall that there are four steps to solving math problems that use recursion.
These steps are also used when writing C functions that use recursion.
1. Identify the argument (or arguments) of a problem. These will be, in general, the
argument (or arguments) for the recursive C function.
2. Express the solution based on the arguments.
3. Determine the simple cases when the solutions are “obvious”. The function has one
(or several) conditions detecting whether this (or these) simple case(s) can be solved
directly. This is usually referred to as the base case.
4. Derive the relationships between complex cases and simpler cases. We call this the
recursive case because the function calls itself with a simplified argument (or several
modified arguments).
A recursive function has the following structure:
return _type func ( a r guments )1
{2
i f ( this is the base case ) /* by checking the arguments */3
{4
solve the problem5
}6
e l s e /* Rec u rsive case */7
{8
func ( simp l ified arguments ) /* fu n ction calls itself */9
}10
}11
A recursive function should first check whether the arguments specify a base case. A
base case means that the function can immediately return the answer. For this reason,
the if condition (or conditions) is called the terminating condition (or conditions) of the
recursive function. The terminating conditions indicate that a base case has been reached.
When the condition is true, the problem is trivial and recursive calls are unnecessary. If the
problem is not simple, then the function enters the recursive case and the function calls itself
with simplified versions of the arguments. The following sections implement the recursive
equations in the previous chapter.
183