Introduction to Computer Science Instructions that Repeat –iterate instruction –while...

Preview:

Citation preview

Introduction to Computer Science

• Instructions that Repeat– iterate instruction

–while instruction

• A Large Program written using Top-Down Design

Unit 4Unit 4

4- 2

Last time, on “Intro to CS”...

• More examples of extending a class, and adding methods

extends

extends

Containers•filled•material•color

Boxeslengthmethod 6

Cereal Boxes

Cylinder

extends

•length•width•height

•radius•height

•type of cerealSoftware Boxes•type of software

extends

Objects made fromthis class have allthe attributes of theclasses above them

4- 3

Multiple Objects

• Objects Sending Messages to Other Objects

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

4- 4

Decomposition

• Good Object Oriented Programming (OOP) means seeing appropriate decomposition

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

Initial Situation

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

Final SituationAreas ofResponsibility

4- 5

Getting Responses from Objects

• Sending messages to objects, getting responses

• Using those responses as parts of other messages

boolean frontIsClearboolean leftIsClearboolean rightIsClear

boolean nextToABeeper

wall-locationsbeeper-locations

myworld

ControlleryLoc

xLocnextToABeeper

STEP 1STEP 2

void movevoid turnLeft

void pickBeepervoid putBeepervoid turnOff

x-locationy-locationdirectionnum-beepers

boolean facingNorthboolean facingSouthboolean facingEastboolean facingWest

boolean anyBeepersInBagint xLocint yLoc

Direct facing

bill

4- 6

Getting Responses from Objects

• Sending messages to objects, getting responses

• Using those responses as parts of other messages

myworld.nextToABeeper(bill.xLoc, bill.yLoc)

4- 7

Using Those Responses to Control Execution

if ( myworld.nextToABeeper(bill.xLoc, bill.yLoc) ) bill.pickBeeper;

4- 8

The iterate Instruction

Provides us with a shorthand notation that tells a robot to repeat an instruction a specified number of times.

iterate <positive-number> times

<instruction>

<instruction> is the body of the iterate instruction. The whole thing we sometimes call an “iterate loop”.

4- 9

Another Way of Defining turnRight

void turnRight {

iterate 3 times

turnLeft;

}

4- 10

Another Way of Defining harvestAFurrow

void harvestAFurrow {

pickBeeper;

iterate 4 times

{

move;

pickBeeper;

}

}

More concise, more general, easier to change number of beepers per furrow.

4- 11

iterate nested within iterate

void makeSquareOfLength6 {

iterate 4 times

{

iterate 6 times

move;turnLeft;

}

}1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

4- 12

iterate nested within iterate

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

After 1 outer loop

void makeSquareOfLength6 {

iterate 4 times

{

iterate 6 times

move;turnLeft;

}

}

4- 13

iterate nested within iterate

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

After 2 outer loops

void makeSquareOfLength6 {

iterate 4 times

{

iterate 6 times

move;turnLeft;

}

}

4- 14

iterate nested within iterate

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

After 3 outer loops

void makeSquareOfLength6 {

iterate 4 times

{

iterate 6 times

move;turnLeft;

}

}

4- 15

iterate nested within iterate

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

After 4 outer loops

void makeSquareOfLength6 {

iterate 4 times

{

iterate 6 times

move;turnLeft;

}

}

4- 16

How Do We Do This?

Assume robot is facing East, and somewhere east of him is a beeper. Tell robot to go to the beeper and pick it up.

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

if ( !myworld.nextToABeeper(...) )

move;if ( !myworld.nextToABeeper(...) )

move;

if ( !myworld.nextToABeeper(...) )

move;pickBeeper;

iterate ? times

move;pickBeeper;

...

4- 17

The while Instruction

The while instruction combines the repetition ability of the iterate instruction with the testing ability of the if instruction.

while <test>

<instruction>

while commands a robot to repeatedly execute an instruction as long as <test> is true.

4- 18

How It Is Executed

• Robot first checks <test> in the current situation

• If <test> is true, robot executes <instruction>, then re-executes the entire while loop

• If <test> if false, robot is finished with the while instruction, and continues by executing instructions that follow the while loop

4- 19

Our Solution to Previous Problem

void goToBeeper {

while ( !myworld.nextToABeeper(xLoc, yLoc) )

move;

}

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

4- 20

Another Example

void clearCornerOfBeepers {

while ( myworld.nextToABeeper(xLoc, yLoc) )

pickBeeper;

}

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

What happens when robot is on a corner with 2 beepers? With zero beepers?

4- 21

Another while Loop

void incorrectClearCornerOfBeepers {

while ( myworld.nextToABeeper(xLoc, yLoc) )

turnLeft;

}

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

What happens when robot is on a corner with zero beepers? With 2 beepers?

4- 22

Another while Loop

void incorrectClearCornerOfBeepers {

while ( myworld.nextToABeeper(xLoc, yLoc) )

turnLeft;

}

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

What happens when robot is on a corner with zero beepers? With 2 beepers?

4- 23

Infinite WHILE Loops

• This is called getting a robot stuck in an infinite loop; it is a kind of intent error

• The ability to have a robot execute an instruction an unknown number of times has dangers as well as benefits

• The while instruction is the only one that can get a robot stuck in an infinite loop

• Check your while instructions carefully to make sure they terminate

4- 24

Formal Property of WHILE

• When (if) a while instruction finishes executing, <test> is known to be false

• If you need to make some <test> true, you write something like:

while <opposite-of-test><instruction>

• For example, to make <frontIsClear> true, write a while loop with <opposite-of-test> replaced by < !frontIsClear >

4- 25

How to Make Sure while instructions terminate?

• Each execution of <instruction> should bring the robot closer to finishing the loop

• In incorrectClearCornerOfBeepers, the repeated turnLeft did not make the robot progress to having picked up all the beepers

void faceNorth {while ( !facingNorth )

turnLeft;}

4- 26

Verifying while Loops

• while loops must be capable of working correctly in an unbounded number of initial situations

• We can use an informal argument to check for probable correctness…

4- 27

Verifying while Loops

• Show the instruction works correctly when <test> is false

• Show that each time the loop body is executed, the robot’s new situation is a simpler (less work) and similar (not very different) version of the old situation

• The while executes correctly and eventually terminates, since each execution of the loop brings the robot closer to having <test> become false

4- 28

For example…

void clearCornerOfBeepers {while ( myworld.nextToABeeper(xLoc, yLoc) )

pickBeeper;}

• If there are no beepers on the corner, the while performs correctly by terminating right away.

• If there are beepers on the corner, there will be one less beeper after the instruction is executed: Simpler (one less beeper) and Similar (robot on same corner)

4- 29

Verifying versus Testing

• Often, instructions are tested in many different initial situations

• These may give us some confidence, but “Testing only shows the presence of bugs, not their absence”

• It helps to carefully simulate the execution of the while loop during its first few and last few repetitions (check out some in the middle, too)

4- 30

When <test> is Checked

void harvestLine {

while (myworld.nextToABeeper(xLoc, yLoc) )

{

pickBeeper;

move;

}

}1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

Robot picks up row of beepers then stops.

4- 31

When <test> is Checked

• Robot checks <test> only before he executes the body of the loop

• He is totally insensitive to <test>while he is executing instructionsinside the loop body

• That is, once the robot starts executing the loop body, he does not recheck <test> until he has completely executed the loop body, and started to re-execute the entire while instruction

4- 32

NOT THIS WAY!

• Some beginning programmers wrongly think the robot checks <test> after each instruction inside the loop body

• NO!!! What would happen in theharvestLine instruction then?

void harvestLine {while ( myworld.nextToABeeper(xLoc,

yLoc) ){

pickBeeper;move;

}}

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

4- 33

Repeating Instructions and Block Structure

1 2 3 4 5 6 7 8 9 10

1

2

3

4

void harvestToWall {pickBeeper;while ( myworld.frontIsClear(xLoc, yLoc, facing) )

{move;pickBeeper;

}}

4- 34

Repeating Instructions and Block Structure

1 2 3 4 5 6 7 8 9 10

1

2

3

4

void harvestToWall {pickBeeper;while ( myworld.frontIsClear(xLoc, yLoc, facing) )

{move;pickBeeper;

}}

4- 35

Repeating Instructions and Block Structure

1 2 3 4 5 6 7 8 9 10

1

2

3

4

void harvestToWall {pickBeeper;while ( myworld.frontIsClear(xLoc, yLoc, facing) )

{move;pickBeeper;

}}

4- 36

Repeating Instructions and Block Structure

1 2 3 4 5 6 7 8 9 10

1

2

3

4

void harvestToWall {pickBeeper;while ( myworld.frontIsClear(xLoc, yLoc, facing) )

{move;pickBeeper;

}}

4- 37

Repeating Instructions and Block Structure

1 2 3 4 5 6 7 8 9 10

1

2

3

4

void harvestToWall {pickBeeper;while ( myworld.frontIsClear(xLoc, yLoc, facing) )

{move;pickBeeper;

}}

4- 38

Repeating Instructions and Block Structure

1 2 3 4 5 6 7 8 9 10

1

2

3

4

Why is first pickBeeper there? What if it were not? How many moves and how many pickBeepers? Could pickBeeper be at the end?

void harvestToWall {pickBeeper;while ( myworld.frontIsClear(xLoc, yLoc, facing) )

{move;pickBeeper;

}}

4- 39

If { and } were forgotten…

1 2 3 4 5 6 7 8 9 10

1

2

3

4

After harvestToWall

1 2 3 4 5 6 7 8 9 10

1

2

3

4

After incorrectHarvestToWallIntent Error

void incorrectHarvestToWall {pickBeeper;while ( myworld.frontIsClear(xLoc, yLoc, facing) )

move;pickBeeper;

}

4- 40

Don’t Forget { and }!

• In what initial situation does this cause an error shutoff (and harvestToWall doesn’t)?

• In what initial situation does this instruction work correctly?

• Can cause intent error, error shutoff, or work!

• Don’t forget { and } when necessary: sometimes causes syntactic error, or worse…

void incorrectHarvestToWall {pickBeeper;while ( myworld.frontIsClear(xLoc, yLoc, facing) )

move;pickBeeper;

}

4- 41

if instructions in while loops

One Initial Situation(zero or one beeper per corner)

The Final Situation1 2 3 4 5 6 7 8 9 10

1

2

3

4

1 2 3 4 5 6 7 8 9 10

1

2

3

4

void sparseHarvestToWall {if ( myworld.nextToABeeper(xLoc, yLoc) )

pickBeeper;while ( myworld.frontIsClear(xLoc, yLoc, facing) )

{move;if (myworld.nextToABeeper(xLoc, yLoc) )

pickBeeper;}

}

Could replace if with instruction pickbeeper-if-present, making it more readable

4- 42

Can Make Even More General

void manyBeeperSparseHarvestToWall {clearCornerOfBeepers;while ( myworld.frontIsClear(xLoc, yLoc, facing) )

{move;clearCornerOfBeepers;

}}

• Try to solve complex problems by looking for similar but simpler problems (to develop structure of solution)

•Strive to re-use your previous work

4- 43

Syntax Error

Programming errors can be hard to spot, but once found are painfully obvious.

“There’s always a reason…”

if ( myworld.nextToABeeper(xLoc, yLoc) )then pickBeeper;

4- 44

A Large Program Written using Top-Down Design

• We want to write a program that has a robot escape from any rectangular room that has an open doorway exactly one block wide.

• After escaping, the robot should turn himself off.

4- 45

The General Plan of Attack

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9 1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

One Initial Situation Final Situationand robot’s Path

4- 46

High-Level Program

main { <Some Constructor creates robot instance>

xxx.goToWall;xxx.turnLeft;xxx.followUntilDoorIsOnRight;xxx.exitDoor;xxx.turnOff;

}New Methods:goToWallfollowUntilDoorIsOnRightexitDoor

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

4- 47

goToWall

void goToWall {while (myworld.frontIsClear(xLoc, yLoc, facing))

move;}

How are we doing so far?

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

4- 48

Beyond-the-horizon Situation

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

One initial situation that causes robot to enter an infinite loop

24 possible corners; 4 directions: 96 different initial situations here. Only 6 of them cause goToWall to fail, i.e., only 7% are “beyond-the-horizon” situations. Random testing is unlikely to be effective.

4- 49

Have Robot “Do the Shuffle”

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

Check for wall in front; if clear, check for wall in front of corner on the right; if clear, go back to original corner and move forward

4- 50

Have Robot “Do the Shuffle”

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

4- 51

Have Robot “Do the Shuffle”

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

4- 52

Have Robot “Do the Shuffle”

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

4- 53

Have Robot “Do the Shuffle”

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

4- 54

Have Robot “Do the Shuffle”

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

4- 55

Have Robot “Do the Shuffle”

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

4- 56

Have Robot “Do the Shuffle”

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

4- 57

Have Robot “Do the Shuffle”

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

Check for wall in front; if clear, check for wall in front of corner on the right; if clear, go back to original corner and move forward

4- 58

goToWall (number 2)

void goToWall {while ( myworld.frontIsClear(xLoc, yLoc, facing) )

shuffle;}

void shuffle {sidestepRight;if ( myworld.frontIsClear(xLoc, yLoc, facing) )

{sidestepBackLeft;move;

}}

4- 59

sidestepping instructions

void sidestepRight {turnRight;move;turnLeft;

}

void sidestepBackLeft {turnLeft;move;turnRight;

}Doing OK?

4- 60

Still not right!

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

•Robot’s right is blocked by wall; he can’t shuffle•What’s the solution?

4- 61

goToWall (number 3)

• If Robot’s right is blocked, have him turn right

void goToWall {if ( myworld.rightIsBlocked(xLoc, yLoc, facing) )

turnRight;else

while ( myworld.frontIsClear(xLoc, yLoc, facing) )

shuffle;}

4- 62

OK, so now what?

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

•Second shuffle causes Robot to perform error-shutoff•We thought his right wouldn’t become blocked•What’s the solution?

4- 63

goToWall (number 4)

• Have Robot always check his right before executing shuffle

void goToWall {while ( myworld.frontIsClear(xLoc, yLoc,

facing) )if (myworld.rightIsBlocked(xLoc, yLoc,

facing) )turnRight;else shuffle;

}

4- 64

followUntilDoorIsOnRight

• We execute this after going to a wall, then executing a turnLeft

• We can thus assume that Robot’s right is blocked by a wall when the instruction starts

• The instruction must stop when Robot senses a door (his right becomes clear)

• While the door is not found, the instruction must make him follow the room’s perimeter

4- 65

An invariant

• An invariant is a condition that must be true during the execution of an instruction

• The invariant for following the perimeter is maintained by having the Robot move forward until reaching a corner, then turn to the left, and continue

4- 66

Robot, find the door!

void followUntilDoorIsOnRight {while ( !myworld.rightIsClear(xLoc, yLoc, facing) )

followPerimeter;}

void followPerimeter {if ( myworld.frontIsClear(xLoc, yLoc, facing) )

move;else turnLeft;

}

When this is finished, Robot’s right hand side will be clear.

4- 67

exitDoor

• We can assume that this is executed only when Robot’s right side is clear

void exitDoor {turnRight;move;

}

4- 68

The Complete Program

class Escaper extends BasicRobot { Definition of turnRight Definition of sidestepRight Definition of sidestepBackLeft Definition of shuffle Definition of goToWall Definition of followPerimeter Definition of followUntilDoorIsOnRight Definition of exitDoor}main {

Escaper bill = new Escaper(...);bill.goToWall;bill.turnLeft;bill.followUntilDoorIsOnRight;bill.exitDoor;bill.turnOff;

} 1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

4- 69

Another strange situation…

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

•What is Robot’s behavior in this situation?

4- 70

Finally this:

1 2 3 4 5

1

2

3

4

5

6 7 8

6

7

8

9

• What does Robot do here?• We want him to turn himself off at corner of 8th

street and 6th avenue• What instruction(s) should be changed to remove

the slight flaw?

Street

Avenues

4- 71

Three things to remember

• Don’t think you’ve got to get the program right the first time

• The most important thing is to write something down on paper. You can make progress then by testing, spotting errors, revising

• If you revise to the point of losing the original thread of solution, maybe you should rewrite the entire program. You’ll be able to use all the knowledge you’ve gained.

Recommended