Last Time:
* The stack: calling multiple funcitons
* Recursion: base case, inductive step
* Recursive functions: factorial, numOnes
Today:
* The recursion "space problem":
* what it is, and how to fix it
* Tailrecursion: a "small" recursive twist
* Testing programs
++++++++++++++++++++++++++++++++++++++++++++++++++++++++
So far, we've introduced the notion of recursive problems and,
correspondingly, recursive functions.
Something is recursive if it
refers to itself.
A problem is recursive if it has:
* One or more trivial base cases
* Other cases defined in terms of smaller problem instances.
(these are "inductive steps")
A function is recursive if it calls itself.
We then gave a few examples of how to map from recursive definitions
to recursive functions: identify the base case, and write that down.
Then, write the inductive step as a recursive call.
Happily, there is a way to rewrite the recursive version to use
(approximately) the same amount of space as is required by the
iterative version.
Consider the following implementation:
int
fact_helper(int n, int result)
// REQUIRES: n >= 0
// EFFECTS: returns result * n!
{
if (n == 0) {
return result;
} else {
return fact_helper(n1, result * n);
}
}
int
factorial(int num)
// REQUIRES: n >= 0
// EFFECTS: returns num!
{
return fact_helper(num, 1);
}
There is an important thing to notice about fact_helper.
For *every*
call to fact_helper:
n! * result
== num!
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is called the "recursive invariant" of fact_helper; an invariant
is something that is always true.
Being able to write down invariants
makes it much easier to write these sorts of functions.
So what's the big deal?
This just looks like a more complicated way
to write the solution.
This is the end of the preview.
Sign up
to
access the rest of the document.
 Winter '08
 NOBLE
 Recursion, Control flow, recursive functions, (int num), recursive version, fact_helper

Click to edit the document details