03+-+Tail+Recursion+and+Intro+to+Testing

03+-+Tail+Recursion+and+Intro+to+Testing - 5/6/2009...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Tail Recursion and Intro to Testin Ve 280 Programming and Introductory Data Structures Tail Recursion and Intro to Testing Recursion Another kind of factorial int fact_helper(int n, int result) // REQUIRES: n >= 0 // EFFECTS: returns result * n! { if (n == 0) { return result; } else { Re-write the recursive version to use the same amount of space as i i d b th return fact_helper(n-1, result * n); } } int factorial(int num) // REQUIRES: n >= 0 // EFFECTS: returns num! { return fact_helper(num, 1); } is required by the iterative version (approximately). Recursion Group Exercise: Another kind of factorial y This function is equivalent to the original factorial. y Try to come up with a proof for int fact_helper(int n, int result) // REQUIRES: n >= 0 // EFFECTS: returns result * n! { if (n == 0) { return result; } else { why. y There are two steps. First, prove the base case, and second, the inductive step. return fact_helper(n-1, result * n); } } int factorial(int num) // REQUIRES: n >= 0 // EFFECTS: returns num! { return fact_helper(num, 1); } Recursion Another kind of factorial y There is an important thing to notice about fact_helper. y For every call to fact_helper: int fact_helper(int n, int result) // REQUIRES: n >= 0 // EFFECTS: returns result * n! { if (n == 0) { return result; } else { n! * result == num! y For the first call, this is easy to see, since: n == num result == 1 return fact_helper(n-1,result*n); } } int factorial(int num) // REQUIRES: n >= 0 // EFFECTS: returns num! { return fact_helper(num, 1); } Recursion Another kind of factorial y For every call to fact_helper: n! * result == num! y For the second call: n == (num - 1) int fact_helper(int n, int result) // REQUIRES: n >= 0 // EFFECTS: returns result * n! { if (n == 0) { return result; } else { result == (1*num) == num Substituting, we get: (num-1)! * num == num! y This is true by inspection. You can continue unwinding if you like. return fact_helper(n-1,result*n); } } int factorial(int num) // REQUIRES: n >= 0 // EFFECTS: returns num! { return fact_helper(num, 1); } Recursion Another kind of factorial y For every call to fact_helper: n! * result == num! Th i i l ld th i i fth l d i
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 4

03+-+Tail+Recursion+and+Intro+to+Testing - 5/6/2009...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online