Discussion 2: Recursion, Tail Recursion
EECS 280
Monday, September 19th, 2011
1
Introduction to Recursion
Recursion is a method of defining a function in terms of itself.
A recursive
function always has two parts:
1.
The base case
The simplest possible instance of the problem that can be
solved.
2.
The recursive case
An expression representing all other instances of the
problem, defined in terms of a slightly simpler instance of the problem.
These are often the only pieces of information you will need to create a recursive
function.
1.1
Ways of Thinking About Recursion
It can be difficult to start forcing your brain to think about problems recur
sively. Analyzing the base case is usually the simplest step, but formulating an
expression for the recursive case is tricky.
1. Ask yourself what the simplest possible case is.
If someone asked you
to solve this problem by yourself, without the aid of code, what problem
would you want? What would require the least work?
2. For every more complicated case (the recursive cases), consider how you
could give
most
of the work to someone else to do, leaving you with nothing
to do but the final step.
Whether this person will break the problem down further (as they will) is
not relevant to you. You trust them to do their job, however they may do
it, and leave you with a simple computation once you have their result.
Don’t think about it too much – if you try to unwind the recursion too
much in your head, you will likely end up overcomplicating the problem.
Try not to think “one step ahead”. Focus on peeling off the outer layer
of the computation (the part you will do later) and giving the rest of the
work to a function to take care of. Try not to think about the fact that the
function that’s doing the rest of the work is the function you’re currently
writing.
1
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
1.2
Examples
We begin with some simple examples to get you accustomed to the idea of
identifying the base cases and recursive cases of simple functions.
A DigitCounting Function
You are tasked counting the number of times
a given digit appears a number (for example, “2” appears in the number
“20122013” three times). How can you do this recursively? Begin with
1
int
CountDigits (int
n,
int
digit)
2
//
REQ:
0
<=
digit
<=
9,
n
>=
0
3
//
EFF:
Returns
the
number
of
times
digit
'
appears
in
n
'
1. What is the simplest
n
you could be given (regardless of the digit
you’re counting)?
This is the end of the preview.
Sign up
to
access the rest of the document.
 Fall '08
 NOBLE
 Recursion, Call stack, Control flow, Recurrence relation, Fibonacci number

Click to edit the document details