Recursion

# Recursion - Lecture 8 Recursion PIC 10B Todd Wittman...

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

1 Lecture 8: Recursion PIC 10B Todd Wittman Operator= vs. Copy Constructor square6 Copy Constructor IntMatrix::IntMatrix (const IntMatrix& right) { rows = right.rows; cols = right.cols; elements = new int[rows*cols]; for (int i=0; i< rows*cols; i++) elements[i] = right.elements[i]; } square6 Assignment Operator IntMatrix& IntMatrix::operator= (const IntMatrix& right) { if (this != &right) { rows = right.rows; cols = right.cols; delete[] elements; elements= new int[rows*cols]; for (int i=0; i<rows*cols; i++) elements[i] = right.elements[i]; } return *this; } •The operator= copies the data in one object into another pre-existing object. •The copy constructor also makes a copy, but it creates a new object from scratch. •What are the differences in code? •When is each called?

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

View Full Document
2 Stuck in an Infinite Loop square6 Recursion is the process of a function calling itself. square6 A dumb example is: int main( ) { cout << “The force be with you!\n”; main(); } square6 This program creates an infinite loop, printing the message forever (or until the computer runs out of memory) . square6 Infinite loops are a common mistake in recursion. square6 A good recursive function should stop. Counting Down... square6 Print out the numbers from N down to 1. void countDown (int N) { cout << N << “\n”; countDown(N-1); return; } Ex N=3 countDown(3) countDown(2) countDown(1) countDown(0 ) ... cout<<3 cout<<2 cout<<1 cout<<0 countDown(2) countDown(1) countDown(0) countDown(-1) square6 We're stuck in an infinite loop again. Why does this function not work?
3 Counting Down...

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