Lecture16-1

# Lecture16-1 - DataStructures CSCI 132 Spring 2012 Lecture...

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

1 Data Structures   CSCI 132, Spring 2012 Lecture 16 Tail Recursion

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

View Full Document
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).

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

View Full Document
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.

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

View Full Document
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 Execution of FactTail num ans num*ans Function Calls 4 1 4 Fact(4, 1):24

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern