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

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

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

View Full Document Right Arrow Icon

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

View Full DocumentRight Arrow Icon

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

View Full DocumentRight Arrow Icon

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

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

Unformatted text preview: Tail Recursion and Intro to Testing EECS 280 Programming and Introductory Data Structures 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 { return fact_helper(n-1, result * n); } } int factorial(int num) // REQUIRES: n >= 0 // EFFECTS: returns num! { return fact_helper(num, 1); } Re-write the recursive version to use the same amount of space as is required by the iterative version (approximatel y). Recursion Group Exercise: Another kind of factorial This function is equivalent to the original factorial. Try to come up with a proof for why. There are two steps. First, prove the base case, and second, 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); } Recursion Another kind of factorial There is an important thing to notice about fact_helper. For every call to fact_helper: n! * result == num! For the first call, 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); } Recursion Another kind of factorial For every call to fact_helper: n! * result == num! For the second call: n == (num - 1) result == (1*num) 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!...
View Full Document

Page1 / 20

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

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

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