Introduction to Computer Science Instructions that Repeat –iterate instruction –while instruction A Large Program written using Top-Down Design Unit 4.

Slides:



Advertisements
Similar presentations
Karel – Making More Complex Decisions IF / THEN / ELSE IF THEN BEGIN Instructions END ELSE BEGIN Instructions END Do these when test = False Do these when.
Advertisements

Nested If Statements While Loops
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Programming in Jessica By Joaquin Vila Prepared by Shirley White Illinois State University Applied Computer Science Department.
Karel The Robot Nested If Statements While Loops Copyright © 2008 by Helene G. Kershner.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Karel The Robot In the beginning… software. Karel the Robot  All robots are controlled by software  Artificially intelligent robots that can “think”
Conditionals How do we solve tasks in which every particular of a task is not specifically known? – A robot needs the ability to survey its immediate environment.
Introduction to Computer Science Returned Values Conditionally Executing Instructions –if instruction –if/else instruction Unit 3.
Introduction to Computer Science Extending Robots’ Vocabularies –New Methods –Top-Down Design –Multiple Robots Unit 2.
Computer Science 1620 Programming & Problem Solving.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Robot? What’s a Robot? Introducing Karel-the-Robot.
SuperCorners. Problem The Corners sample robot has a simple strategy: first, move into a corner of the arena, and second sweep the gun back and forth.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Chapter 5 Conditionally Executing Instructions
1 karel_part5_loops Iteration (Loops) Loops repeat a set of instructions Two types of loops: –Definite loops ( for ) perform instructions explicit (known)
Ch. 2 1 Karel – Primitive Instructions Basic tools with which all problems are solved (analogies: LeftSpinngingRobot, RightSpinningRobot, GuardRobot, etc)
Karel J Robot An introduction to BlueJ and Object- Oriented Programming.
1 Ch. 7 Recursion similar to iteration in that you repeatedly do a little bit of the task and then “loop” again and work on a smaller piece - eventually.
Maze Challenge Maze Challenge activity > TeachEngineering.org
Karel J. Robot A Gentle Introduction to the Art of Object Oriented Programming.
Karel the Robot A Gentle Introduction to the Art of Programming.
CSI 3125, Axiomatic Semantics, page 1 Axiomatic semantics The assignment statement Statement composition The "if-then-else" statement The "while" statement.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
CPS120 Introduction to Computer Science Iteration (Looping)
Programming Errors Lexical errors – occur whenever Karel reads a word that is not in his vocabulary. Example in English: We are asking directions and instead.
Thanks to Dr. Kris Schindler for this (and all Karel the Robot slides)
CPS120: Introduction to Computer Science Decision Making in Programs.
MA 1128: Lecture 17 – 6/17/15 Adding Radicals Radical Equations.
Recursion – means to recur or to repeat – A different way to get a robot to repeat an action A programming language that allows recursive definitions (and.
Karel J. Robot Tool for learning OOP (Lecture covers Ch. 1 and 2)
1 karel_part2_Inheritance Extending Robots Tired of writing turnRight every time you start a new karel project. How do we avoid re-writing code all the.
1 Karel – Chapter 6 Instructions That Repeat Note: Original slides provided by and modified for Mr. Smith’s AP Computer Science.
1 Ch. 6 Iteration (Loops) Loops repeat a set of instructions Two types of loops: –Definite loops ( for ) perform instructions explicit number of times.
1 Karel – Chapter 5 Conditionally Executing Instructions Note: Original slides provided by and modified for Mr. Smith’s AP Computer.
1 Karel J Robot OOP approach to learning computer science “Its study involves development of the ability to abstract the essential features of a problem.
15-100: Introduction to Programming w/ Java * Ananda Gunawardena -- Lecture – School of Computer Science – Phone : (x81559) – Office: Wean Hall.
Chapter 5.  We’ve been using UrRobot – knows only 5 things  Let’s now use a new type of Robot: Robot!  i.e. – public class MileMover extends Robot.
CPS120 Introduction to Computer Science Iteration (Looping)
Introduction to OOP in VB.NET using Robots ACSE Conference, Nov 2004 Michael Devoy Monsignor Doyle C.S.S., Cambridge
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
Extending Karel’s Vocabulary This PPT originated with Dr. Judy Hankins Modifications have been done by Dr. Untch & Dr. Cripps.
Programming in Karel Eric Roberts CS 106A January 6, 2016.
Introduction to Computer Science
Ch. 2 1 Karel – Primitive Instructions Basic tools with which all problems are solved (analogies: carpentry, geometry) –move() –turnLeft() –putBeeper()
Karel J. Robot Chapter 6 Instructions That Repeat.
Mile-long hurdle race Suppose that we want to program Karel to run a one-mile long hurdle race, where vertical wall sections represent hurdles. The hurdles.
Karel the Robot – Review Primitive Commands move pickbeeper putbeeper turnleft turnoff Karel’s program statements are separated by a semicolon (;) Copyright.
Repetition everywhere – comparing while in a method and as an event Susan Rodger Duke University July 2010.
CS162 - Topic #10 Lecture: Recursion –The Nature of Recursion –Tracing a Recursive Function –Work through Examples of Recursion Programming Project –Discuss.
1 Karel J. Robot Chapter 5 Conditionally Executing Instructions.
Karel J. Robot Chapter 6 Instructions That Repeat.
CS 106A, Lecture 3 Problem-solving with Karel
Mile-long hurdle race Suppose that we want to program Karel to run a one-mile long hurdle race, where vertical wall sections represent hurdles. The hurdles.
Chapter 4 Repetition Statements (loops)
In the beginning… software
Copyright © 2008 by Helene G. Kershner
Loops We have already seen instances where a robot needs to repeat instructions to perform a task turnRight(); moveMile(); Harvesting beepers in a field.
Copyright © 2008 by Helene G. Kershner
Karel J Robot.
Karel – Primitive Instructions
Karel J Robot Chapter 6.
CS 106A, Lecture 2 Programming with Karel
Creativity in Algorithms
Algorithm and Ambiguity
Nested If Statements While Loops
Topics Introduction to Repetition Structures
Iteration (Loops) Loops repeat a set of instructions
Presentation transcript:

Introduction to Computer Science Instructions that Repeat –iterate instruction –while instruction A Large Program written using Top-Down Design Unit 4

4- 2 Last time, on “Intro to CS”... More examples of extending a class, and adding methods

4- 3 Multiple Objects Objects Sending Messages to Other Objects

4- 4 Decomposition Good Object Oriented Programming (OOP) means seeing appropriate decomposition

4- 5 Getting Responses from Objects Sending messages to objects, getting responses Using those responses as parts of other messages

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 times 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; }

4- 12 iterate nested within iterate After 1 outer loop void makeSquareOfLength6 { iterate 4 times { iterate 6 times move; turnLeft; }

4- 13 iterate nested within iterate After 2 outer loops void makeSquareOfLength6 { iterate 4 times { iterate 6 times move; turnLeft; }

4- 14 iterate nested within iterate After 3 outer loops void makeSquareOfLength6 { iterate 4 times { iterate 6 times move; turnLeft; }

4- 15 iterate nested within iterate 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 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 while commands a robot to repeatedly execute an instruction as long as is true.

4- 18 How It Is Executed Robot first checks in the current situation If is true, robot executes, then re-executes the entire while loop If 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; }

4- 20 Another Example void clearCornerOfBeepers { while ( myworld.nextToABeeper(xLoc, yLoc) ) pickBeeper; } 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; } 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; } 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, is known to be false If you need to make some true, you write something like: while For example, to make true, write a while loop with replaced by

4- 25 How to Make Sure while instructions terminate? Each execution of 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 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 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 is Checked void harvestLine { while (myworld.nextToABeeper(xLoc, yLoc) ) { pickBeeper; move; } Robot picks up row of beepers then stops.

4- 31 When is Checked Robot checks only before he executes the body of the loop He is totally insensitive to while he is executing instructions inside the loop body That is, once the robot starts executing the loop body, he does not recheck 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 after each instruction inside the loop body NO!!! What would happen in the harvestLine instruction then? void harvestLine { while ( myworld.nextToABeeper(xLoc, yLoc) ) { pickBeeper; move; } 

4- 33 Repeating Instructions and Block Structure void harvestToWall { pickBeeper; while ( myworld.frontIsClear(xLoc, yLoc, facing) ) { move; pickBeeper; }

4- 34 Repeating Instructions and Block Structure void harvestToWall { pickBeeper; while ( myworld.frontIsClear(xLoc, yLoc, facing) ) { move; pickBeeper; }

4- 35 Repeating Instructions and Block Structure void harvestToWall { pickBeeper; while ( myworld.frontIsClear(xLoc, yLoc, facing) ) { move; pickBeeper; }

4- 36 Repeating Instructions and Block Structure void harvestToWall { pickBeeper; while ( myworld.frontIsClear(xLoc, yLoc, facing) ) { move; pickBeeper; }

4- 37 Repeating Instructions and Block Structure void harvestToWall { pickBeeper; while ( myworld.frontIsClear(xLoc, yLoc, facing) ) { move; pickBeeper; }

4- 38 Repeating Instructions and Block Structure Why is first pickBeeper there? What if it were not? How many move s and how many pickBeeper s? Could pickBeeper be at the end? void harvestToWall { pickBeeper; while ( myworld.frontIsClear(xLoc, yLoc, facing) ) { move; pickBeeper; }

4- 39 If { and } were forgotten… After harvestToWall After incorrectHarvestToWall Intent 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 Situation 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 One Initial SituationFinal Situation and robot’s Path

4- 46 High-Level Program main { xxx.goToWall; xxx.turnLeft; xxx.followUntilDoorIsOnRight; xxx.exitDoor; xxx.turnOff; } New Methods: goToWall followUntilDoorIsOnRight exitDoor

4- 47 goToWall void goToWall { while (myworld.frontIsClear(xLoc, yLoc, facing)) move; } How are we doing so far?

4- 48 Beyond-the-horizon Situation 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” 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”

4- 51 Have Robot “Do the Shuffle”

4- 52 Have Robot “Do the Shuffle”

4- 53 Have Robot “Do the Shuffle”

4- 54 Have Robot “Do the Shuffle”

4- 55 Have Robot “Do the Shuffle”

4- 56 Have Robot “Do the Shuffle”

4- 57 Have Robot “Do the Shuffle” 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! 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? 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; }

4- 69 Another strange situation… What is Robot’s behavior in this situation?

4- 70 Finally this: 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? StreetStreet 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.