Lecture16-1 - 1 Data Structures CSCI 132 Spring 2012...

Info iconThis preview shows pages 1–7. 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: 1 Data Structures CSCI 132, Spring 2012 Lecture 16 Tail Recursion 2 Recall Recursive Skating void skateLaps( int n) { if ( n < = 0 ) { //do nothing } else { cout << "Skating 1 lap." << endl; skateLaps( n - 1); } } Base Case General Case 3 Tail Recursion • When the recursive function call is the last thing that occurs in the recursive function, this is called a Tail Recursion . • In a tail recursion, there are no pending operations . • Any tail recursion can be written as an iteration (a loop). 4 Iterating skateLaps void skateLaps( int n) { while (n > 0 ) { cout << "Skating 1 lap." << endl; n = n - 1; } } 5 Factorial Revisited int Fact (int n) { if (n <= 0) { return 1; } else { return n * Fact (n - 1); } } Is this a tail recursion? No. Can we write this as a tail recursion? Yes! Keep track of the answer in a parameter that gets passed on. 6 Tail Recursion Factorial int factTail (int num, int ans) { if (num <= 0) { return ans; } else { return factTail(num - 1, num*ans); } } int factIter (int n) { //Helper function to initialize ans return factTail(n, 1); } 7...
View Full Document

This document was uploaded on 03/09/2012.

Page1 / 33

Lecture16-1 - 1 Data Structures CSCI 132 Spring 2012...

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

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