66
CSC211 Data Structures Lecture 13 Lecture 13 Recursive Thinking Recursive Thinking Instructor: Prof. Xiaoyan Instructor: Prof. Xiaoyan Li Li Department of Computer Department of Computer Science Science Mount Holyoke College Mount Holyoke College

CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Embed Size (px)

Citation preview

Page 1: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

CSC211 Data Structures CSC211 Data Structures

Lecture 13Lecture 13Recursive ThinkingRecursive Thinking

Instructor: Prof. Xiaoyan LiInstructor: Prof. Xiaoyan LiDepartment of Computer Science Department of Computer Science

Mount Holyoke CollegeMount Holyoke College

Page 2: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Review Lecture 12: Summary and Homework on stacks and queues

Review Lecture 12: Summary and Homework on stacks and queues

Stacks (Read Chapter 7)Stacks (Read Chapter 7) Self-Test: 1-5, 13-18 Self-Test: 1-5, 13-18 What is the difference between the top and pop operations of a stack?What is the difference between the top and pop operations of a stack? What is the typical implementation of an STL stack?What is the typical implementation of an STL stack?

Queues (Read Sections 8.1 – 8.3)Queues (Read Sections 8.1 – 8.3) Self-Test: 1-5, 10,18-21Self-Test: 1-5, 10,18-21 What queue functions are used to avoid queue overflow and queue What queue functions are used to avoid queue overflow and queue

under flow?under flow? Can a single program use both a stack and a queue?Can a single program use both a stack and a queue?

Priority Queues (Read Section 8.4)Priority Queues (Read Section 8.4) Self-Test: 25-27Self-Test: 25-27 How priorities are specified?How priorities are specified? Suppose that you create a priority queue of double numbers, inserting Suppose that you create a priority queue of double numbers, inserting

the numbers 10, 20, 30. Which number will come out first?the numbers 10, 20, 30. Which number will come out first?

Page 3: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Stacks have many applications.Stacks have many applications. The application (n-queen problem) we have shown The application (n-queen problem) we have shown

is called is called backtrackingbacktracking.. The key to backtracking: Each choice is recorded The key to backtracking: Each choice is recorded

in a stack.in a stack. When you run out of choices for the current When you run out of choices for the current

decision, you pop the stack, and continue trying decision, you pop the stack, and continue trying different choices for the previous decision.different choices for the previous decision.

Summary of stack for backtracking Summary of stack for backtracking

Page 4: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Outline of This LectureOutline of This Lecture

Start with an Example of RecursionStart with an Example of Recursion ““racing car” – not in the textbookracing car” – not in the textbook using slides (provided by the authors)using slides (provided by the authors)

Recursive Thinking: General FormRecursive Thinking: General Form Tracing Recursive Calls Tracing Recursive Calls

using blackboard to show the conceptsusing blackboard to show the concepts A Closer Look at RecursionA Closer Look at Recursion

activation record and runtime stackactivation record and runtime stack

Page 5: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Chapter 9 introduces the technique of recursive programming.

As you have seen, recursive programming involves spotting smaller occurrences of a problem within the problem itself.

This presentation gives an additional example, which is not in the book.

Recursive ThinkingRecursive Thinking

Data StructuresData Structuresand Other Objectsand Other ObjectsUsing C++Using C++

Page 6: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Presentation copyright 1997 Addison Wesley Longman,For use with Data Structures and Other Objects Using C++by Michael Main and Walter Savitch.

Some artwork in the presentation is used with permission from Presentation Task Force(copyright New Vision Technologies Inc) and Corel Gallery Clipart Catalog (copyrightCorel Corporation, 3G Graphics Inc, Archive Arts, Cartesia Software, Image ClubGraphics Inc, One Mile Up Inc, TechPool Studios, Totem Graphics Inc).

Students and instructors who use Data Structures and Other Objects Using C++ are welcometo use this presentation however they see fit, so long as this copyright notice remainsintact.

The Car Racer Slides were modified fromThe Car Racer Slides were modified from

Page 7: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

A Car ObjectA Car Object

To start the example, think about your favorite family car

Page 8: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

A Car ObjectA Car Object

To start the example, think about your favorite family car

Page 9: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

A Car ObjectA Car Object

To start the example, think about your favorite family car

Page 10: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

A Car ObjectA Car Object

To start the example, think about your favorite family car

Page 11: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

A Car ObjectA Car Object

To start the example, think about your favorite family car

Imagine that the car is controlled by a radio signal from a computer

Page 12: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

A Car ClassA Car Class

class Car {public: . . .};

To start the example, think about your favorite family car

Imagine that the car is controlled by a radio signal from a computer

The radio signals are generated by activating member functions of a Car object

Page 13: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

class Car{public: Car(int car_number); void move( ); void turn_around( ); bool is_blocked( );private: { We don't need to know the private fields! } . . .};

Member Functions for the Car ClassMember Functions for the Car Class

Page 14: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

int main( ){ Car racer(7);

. . .

The ConstructorThe Constructor

When we declare a Car

and activate the constructor, the computer makes a radio link with a car that has a particular number.

Page 15: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

int main( ){ Car racer(7);

racer.turn_around( ); . . .

The turn_around FunctionThe turn_around Function

When we activate turn_around, the computer signals the car to turn 180 degrees.

Page 16: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

int main( ){ Car racer(7);

racer.turn_around( ); . . .

The turn_around FunctionThe turn_around Function

When we activate turn_around, the computer signals the car to turn 180 degrees.

Page 17: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

int main( ){ Car racer(7);

racer.turn_around( ); racer.move( ); . . .

The move FunctionThe move Function

When we activate move, the computer signals the car to move forward one foot.

Page 18: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

int main( ){ Car racer(7);

racer.turn_around( ); racer.move( ); . . .

The move FunctionThe move Function

When we activate move, the computer signals the car to move forward one foot.

Page 19: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

int main( ){ Car racer(7);

racer.turn_around( ); racer.move( ); if (racer.is_blocked( ) ) cout << "Cannot move!"; . . .

The is_blocked( ) FunctionThe is_blocked( ) Function

The is_blocked member function detects barriers.

Page 20: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Your MissionYour Mission

Write a function which will move a Car forward until it reaches a barrier...

Page 21: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Your MissionYour Mission

Write a function which will move a Car forward until it reaches a barrier...

Page 22: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Your MissionYour Mission

Write a function which will move a Car forward until it reaches a barrier...

Page 23: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Your MissionYour Mission

Write a function which will move a Car forward until it reaches a barrier...

...then the car is turned around...

Page 24: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Your MissionYour Mission

Write a function which will move a Car forward until it reaches a barrier...

...then the car is turned around... ...and returned to its original location, facing the

opposite way.

Page 25: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Your MissionYour Mission

Write a function which will move a Car forward until it reaches a barrier...

...then the car is turned around... ...and returned to its original location, facing the

opposite way.

Page 26: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Your MissionYour Mission

Write a function which will move a Car forward until it reaches a barrier...

...then the car is turned around... ...and returned to its original location, facing the

opposite way.

void ricochet(Car& moving_car);

Page 27: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

void ricochet(Car& moving_car);

Page 28: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

moving_car.move( );. . .

Page 29: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );. . .

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);This makes the problem a bit smaller. For example, if the car started 100 feet from the barrier...

100 ft.

Page 30: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );. . .

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);This makes the problem a bit smaller. For example, if the car started 100 feet from the barrier... then after activating move once, the distance is only 99 feet.

99 ft.

Page 31: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );. . .

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

We now have a smaller version of the same problem that we started with.

99 ft.

Page 32: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);. . .

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

Make a recursive call to solve the smaller problem.

99 ft.

Page 33: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);. . .

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

The recursive call will solve the smaller problem.

99 ft.

Page 34: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);. . .

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

The recursive call will solve the smaller problem.

Page 35: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);. . .

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

The recursive call will solve the smaller problem.

Page 36: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);. . .

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

The recursive call will solve the smaller problem.

Page 37: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);. . .

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

The recursive call will solve the smaller problem.

Page 38: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);. . .

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

The recursive call will solve the smaller problem.

Page 39: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);. . .

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

The recursive call will solve the smaller problem.

Page 40: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);. . .

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

The recursive call will solve the smaller problem.

Page 41: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);. . .

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

The recursive call will solve the smaller problem.

Page 42: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);. . .

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

The recursive call will solve the smaller problem.

99 ft.

Page 43: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);. . .

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

What is the last step that's needed to return to our original location ?

99 ft.

Page 44: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);moving_car.move( );

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

What is the last step that's needed to return to our original location ?

100 ft.

Page 45: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);moving_car.move( );

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

This recursive function follows a common pattern that you should recognize.

Page 46: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);moving_car.move( );

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

When the problem is simple, solve it with no recursive call. This is the base case or the stopping case.

Page 47: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);moving_car.move( );

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

When the problem is more complex, start by doing work to create a smaller version of the same problem...

Page 48: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);moving_car.move( );

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

...use a recursive call to completely solve the smaller problem...

Page 49: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

moving_car.move( );ricochet(moving_car);moving_car.move( );

Pseudocode for ricochetPseudocode for ricochet

if moving_car.is_blocked( ), then the car is already at the barrier. In this case, just turn the car around.

Otherwise, the car has not yet reached the barrier, so start with:

void ricochet(Car& moving_car);

...and finally do any work that's needed to complete the solution of the original problem..

Page 50: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Implementation of ricochetImplementation of ricochet

void ricochet(Car& moving_car){ if (moving_car.is_blocked( )) moving_car.turn_around( ); // Base case else { // Recursive pattern moving_car.move( ); ricochet(moving_car); moving_car.move( ); }}

Look for this pattern in the other examples of Chapter 9.

Page 51: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

An ExerciseAn Exercise

Can you write Can you write ricochet as a new ricochet as a new member function of member function of the Car class, the Car class, instead of a instead of a separate function?separate function?

You have 2 minutes towrite the implementation.

void Car::ricochet( ){ . . .

Page 52: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

An ExerciseAn Exercise

void Car::ricochet( ){ if (is_blocked( )) turn_around( ); // Base case else { // Recursive pattern move( ); ricochet( ); move( ); }}

One solution:

Page 53: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Recursive Thinking: General FormRecursive Thinking: General Form

Recursive Calls Recursive Calls Suppose a problem has one or more cases in which Suppose a problem has one or more cases in which

some of the subtasks are simpler versions of the some of the subtasks are simpler versions of the original problem. These subtasks can be solved by original problem. These subtasks can be solved by recursive callsrecursive calls

Stopping Cases /Base CasesStopping Cases /Base Cases A function that makes recursive calls must have one or A function that makes recursive calls must have one or

more cases in which the entire computation is fulfilled more cases in which the entire computation is fulfilled without recursion. These cases are called stopping without recursion. These cases are called stopping cases or base casescases or base cases

Page 54: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Tracing Recursive Calls: RicochetTracing Recursive Calls: Ricochet

void Car::ricochet( ){ if (is_blocked( ))A. turn_around( ); // Base case else { // Recursive patternB. move( );C. ricochet( );D. move( );E }}

Do it by hand if car is 4 feet away from the barrier

Page 55: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

A Close Look at Ricochet RecursionA Close Look at Ricochet Recursion

The recursive case and the stopping caseThe recursive case and the stopping case

Activation recordActivation record The return location only in this example – other The return location only in this example – other

information is kept in the object racer information is kept in the object racer

The running stack The running stack The collection of the activation records is stored in a The collection of the activation records is stored in a

stack data structurestack data structure

Page 56: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Example 2: Write Number VerticallyExample 2: Write Number Vertically

TaskTask Write a non-negative integer to the screen with Write a non-negative integer to the screen with

its decimal digits stacked verticallyits decimal digits stacked vertically for example:for example:

Input

1234

Output:1

2

3

4

Page 57: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

A possible functionA possible function

void write_vertical (unsigned int number)// precondition: number >=0// Postcondition: The digits of number have been written, stacked vertically.{ assert(number>=0); do {

cout << number % 10 << endl; // Write a digit number = number / 10; } while (number !=0); }

Write an integer number vertically

Input

1234

Output:4

3

2

1

Page 58: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Approach 1: using a stackApproach 1: using a stack

void stack_write_vertical (unsigned int number)// Postcondition: The digits of number have been written, stacked vertically.{ stack<int> s; do {

s.push(number % 10); // push a digit in the stack number = number / 10; } while (number !=0); while (!(s.empty())) { cout << s.top()<< endl; //print a digit from the stack s.pop(); }}

Write an integer number vertically

Page 59: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Approach 2: Using RecursionApproach 2: Using Recursion

void recursive_write_vertical(unsigned int number)// Postcondition: The digits of number have been written, stacked vertically.{ if (number < 10) // stopping case

cout << number << endl; // Write the one digit else // including recursive calls {

recursive_write_vertical(number/10); // Write all but the last digit

cout << number % 10 << endl; // Write the last digit

}}

Write an integer number vertically

Page 60: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Tracing Recursive CallsTracing Recursive Calls

void recursive_write_vertical_2(unsigned int number)// Postcondition: The digits of number have been written, stacked vertically.{ if (number < 10) // stopping case

A cout << number << endl; // Write the one digit else // including recursive calls {

B recursive_write_vertical(number/10); // Write all but the last digit

C cout << number % 10 << endl; // Write the last digit

D }}

Write an integer number vertically

Page 61: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

A Closer Look at the RecursionA Closer Look at the Recursion

Recursive FunctionRecursive Function Recursive callsRecursive calls Stopping (Base) casesStopping (Base) cases

Run-time StackRun-time Stack the collection of activation records is stored in the stackthe collection of activation records is stored in the stack

Activation Record - a special memory block includingActivation Record - a special memory block including return location of a function callreturn location of a function call values of the formal parameters and local variablesvalues of the formal parameters and local variables

Page 62: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Recursive Thinking: General FormRecursive Thinking: General Form

Recursive Calls Recursive Calls Suppose a problem has Suppose a problem has one or moreone or more cases in which cases in which

some of the subtasks are simpler versions of the some of the subtasks are simpler versions of the original problem. These subtasks can be solved by original problem. These subtasks can be solved by recursive callsrecursive calls

Stopping Cases /Base CasesStopping Cases /Base Cases A function that makes recursive calls must have A function that makes recursive calls must have one or one or

moremore cases in which the entire computation is fulfilled cases in which the entire computation is fulfilled without recursion. These cases are called stopping without recursion. These cases are called stopping cases or base casescases or base cases

Page 63: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Self-Tests and More Complicated ExmaplesSelf-Tests and More Complicated Exmaples

An Extension of write_vertical An Extension of write_vertical handles all integers including negative oneshandles all integers including negative ones Hints: you can have more than one recursive Hints: you can have more than one recursive

calls or stopping cases in your recursive calls or stopping cases in your recursive functionfunction

Page 64: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

super_write_vertical- Write any integer number vertically

super_write_vertical- Write any integer number vertically

void super_write_vertical(int number)// Postcondition: The digits of the number have been written, stacked vertically.// If number is negative, then a negative sign appears on top.// Library facilities used: iostream.h, math.h{

}

Page 65: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

super_write_vertical- Write any integer number vertically

super_write_vertical- Write any integer number vertically

void super_write_vertical(int number)// Postcondition: The digits of the number have been written, stacked vertically.// If number is negative, then a negative sign appears on top.// Library facilities used: iostream.h, math.h{ if (number < 0) { cout << '-' << endl; // print a negative sign super_write_vertical(abs(number)); // abs computes absolute value // This is Spot #1 referred to in the text. } else if (number < 10) cout << number << endl; // Write the one digit else { super_write_vertical(number/10); // Write all but the last digit // This is Spot #2 referred to in the text. cout << number % 10 << endl; // Write the last digit }}

Page 66: CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College

Homework:Homework:

Reading: Section 9.1Reading: Section 9.1 Self-Test: Exercises 1-8Self-Test: Exercises 1-8 Advanced Reading: Section 9.2Advanced Reading: Section 9.2 Assignment 5 will be online tonightAssignment 5 will be online tonight