CS106X
Handout 19
Winter 2008
January 30, 2008
Introduction to Recursion
Today we'll start working with one of CS106X’s neatest ideas: recursion.
Recursion is the
trick whenever the problem to be solved can be broken down into virtually identical (though
smaller) subproblems.
The classic introductory example employing recursion is an
implementation of the
factorial
function:
int factorial(int n)
{
if (n == 0) return 1;
return n * factorial(n  1);
}
Readings from the Text:
Today's Lecture
: Start Chapters 4 and 5.
Friday’s Lecture
: Continue with Chapters 4 and 5
Every recursive function lists a sequence of base cases, and then one or more recursive cases.
Occasionally, the problem to be solved is so simple that we can return or terminate execution
without any further computation.
The first of the two lines in
factorial
is an example of
such a base case—
0!
is always
1
and is easily understood.
However, whenever the specified
integer
n
is larger than
0
, it helps to calculate
(n1)!
and multiply the result of that
computation by
n
itself.
That's precisely what the recursive call is doing.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview.
Sign up
to
access the rest of the document.
 Winter '08
 Cain,G
 Recursion, Fractal, Benoît Mandelbrot, Exhaustive recursive function, string rest

Click to edit the document details