Unlock access to all the studying documents.
View Full Document
1
This lecture demonstrates a typical pattern that arises in recursive
functions. The lecture can be given shortly before or shortly after the
students have read Section 9.1.
❐Chapter 9 introduces the technique
of recursive programming.
❐As you have seen, recursive
programming involves spotting
Recursive Thinking
2
In this lecture, we’re going to design a recursive function which
A Car Object
❐To start the example,
think about your favorite
family car
3
A Car Object
❐To start the example,
think about your favorite
family car
4
A Car Object
❐To start the example,
think about your favorite
family car
5
A Car Object
❐To start the example,
think about your favorite
family car
6
A Car Object
❐To start the example,
think about your favorite
family car
7
The radio signals themselves are generated by writing a program which
uses a new object type called a Car. Each time one of the car methods
A Car Class
class Car
{
public:
. . .
❐To start the example,
think about your favorite
family car
❐Imagine that the car is
controlled by a radio
8
class Car
{
public:
Car(int car_number);
Member Functions for the Car Class
9
This example demonstrates the usage of the constructor. In this
int main( )
{
Car racer(7);
The Constructor
When we declare a Car
and activate the
constructor, the computer
10
After the connection is made, we can activate other member functions
of racer. In this example, we are activating
int main( )
{
The turn_around Function
When we activate
turn_around, the computer
11
Here’s an example of the third Car member function in action. When
we activate
int main( )
{
The move Function
When we activate move,
the computer signals the
12
int main( )
{
Car racer(7);
The move Function
When we activate move,
the computer signals the
car to move forward one
13
The last Car member function is a boolean function called is_blocked.
A question: What will racer.is_blocked return in this example?
Another question: Can you state a good precondition for the move
member function?
int main( )
{
Car racer(7);
The is_blocked( ) Function
The is_blocked member
function detects barriers.
14
Your Mission
15
Your Mission
❐Write a function which will move a Car forward until it
reaches a barrier…
16
Your Mission
❐Write a function which will move a Car forward until it
reaches a barrier…
17
Your Mission
❐Write a function which will move a Car forward until it
reaches a barrier…
18
Your Mission
❐Write a function which will move a Car forward until it
reaches a barrier…
19
Your Mission
❐Write a function which will move a Car forward until it
reaches a barrier…
20
Your Mission
❐Write a function which will move a Car forward until it
reaches a barrier…
void ricochet(Car& moving_car);