{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

03-tailrecursion.student

# 03-tailrecursion.student - Last Time The stack calling...

This preview shows pages 1–3. Sign up to view the full content.

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 * Tail-recursion: 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 re-write 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(n-1, 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.

{[ snackBarMessage ]}

### Page1 / 6

03-tailrecursion.student - Last Time The stack calling...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online