
1
CS 112 Introduction to
Programming
Lecture #28:
Recursive Programming
http://flint.cs.yale.edu/cs112/
2
Recursive Programming
rRecursion: a method calls itself
rRecursion is often used
to search for a solution
to a problem, e.g.,
mHanoi Towers
mMaze search
mChange maker: how
many ways of making changes
to a one-dollar bill?
rRecursion is also useful for modeling
physical world
mFractal images
1 2 3
3
Recursive Thinking
rA recursive definition is one which uses the
word or concept being defined in the
definition itself
rWhen defining an English word, a recursive
definition is often not helpful, e.g.,
mA is not B; B is not A
rBut in other situations, a recursive definition
can be an appropriate way to express a
concept
rBefore applying recursion to programming, it
is best to practice thinking recursively
4
Recursive Definition: LIST
rConsider the following list of numbers:
24, 88, 40, 37
rSuch a list can be defined as
A LIST is a: number
or a: number comma LIST
rThat is, a LIST is defined to be a single number, or a number
followed by a comma followed by a LIST
rThe concept of a LIST is used to define itself
5
Recursive Definitions:
Matching LIST Definition
number comma LIST
24 , 88, 40, 37
number comma LIST
88 , 40, 37
number comma LIST
40 , 37
number
37
rThe recursive part of the LIST definition is
used several times, terminating with the non-
recursive part.
6
Recursive Definitions: Factorial
rN!, for any positive integer N, is defined to be
the product of all integers between 1 and N
inclusive
rThis definition can be expressed recursively
as:
1! = 1
N! = N * (N-1)!
rThe concept of the factorial is defined in
terms of another factorial