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.

Slides:



Advertisements
Similar presentations
1 karel_IF_part1 Conditional Statements Flavor 1: if ( ) { } For now: these are method invokations (see next slide)
Advertisements

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.
Copyright, Joseph Bergin
Nested If Statements While Loops
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Karel’s Sensory Equipment This PPT originated with Dr. Untch and Dr. Hankins Modifications have been made by Dr. Cripps.
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.
Topic 6 – Repetition and Loops. CISC 105 – Topic 6 Program Repetition Repetition refers to the repeats of certain program statements within a program.
Introduction to Computer Science Instructions that Repeat –iterate instruction –while instruction A Large Program written using Top-Down Design Unit 4.
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.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
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.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
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.
Karel J. Robot A Gentle Introduction to the Art of Object Oriented Programming.
Karel the Robot A Gentle Introduction to the Art of Programming.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
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)
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
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.
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.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
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.
Loops George Mason University. Loop Structure Loop- A structure that allows repeated execution of a block of statements Loop body- A block of statements;
15-100: Introduction to Programming w/ Java * Ananda Gunawardena -- Lecture – School of Computer Science – Phone : (x81559) – Office: Wean Hall.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
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.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Karel J. Robot Chapter 6 Instructions That Repeat.
© The McGraw-Hill Companies, 2006 Chapter 3 Iteration.
Karel the Robot – Review Primitive Commands move pickbeeper putbeeper turnleft turnoff Karel’s program statements are separated by a semicolon (;) Copyright.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
1 Karel – Chapter 5 Conditionally Executing Instructions Note: Original slides provided by and modified for Mr. Smith’s AP Computer.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
Karel the Robot – Review Primitive Commands move pickbeeper putbeeper turnleft Turnoff Karel’s program statements are separated by a semicolon (;) Copyright.
Karel the Robot – Review Primitive Commands move pickbeeper putbeeper turnleft Turnoff Karel’s program statements are separated by a semicolon (;) Copyright.
1 Karel J. Robot Chapter 5 Conditionally Executing Instructions.
1 Chapter 5 Karel J Robot 2 Chapter 5 Chapter 5 Conditional Statements Flavor 1: if ( ) { } For now: these are method invocations (see next slide)
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.
Eric Roberts and Jerry Cain
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 Chapter 6.
CS 106A, Lecture 2 Programming with Karel
Quick Test What do you mean by pre-test and post-test loops in C?
JavaScript: Control Statements.
Scratch: selection / branching/ if / If…else / compound conditionals / error trapping by Mr. Clausen.
slides courtesy of Eric Roberts
Nested If Statements While Loops
Iteration (Loops) Loops repeat a set of instructions
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Presentation transcript:

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 are only one block high and are randomly placed between any two corners in the race course. One possible race course is shown below.

Strategy? Karel could run this race by jumping up between every pair of corners. Is this an appropriate strategy?

Jumping up between corners, whether a hurdle was between them or not, would slow Karel down. Instead, program Karel to move straight ahead when it can, and to jump over hurdles only when it must. The program could then consist of 8 AdvanceACorner() instructions. The definition of AdvanceACorner() can be written using stepwise refinement as follows:

void AdvanceACorner() { if (frontIsClear) Move(); else JumpHurdle(); } Notice we have used a new command JumpHurdle() that must now be defined.

We continue our refinement by defining JumpHurdle() to be void JumpHurdle() { JumpUp(); Move(); JumpDown(); }

To finish the problem, we write JumpUp() and JumpDown() Void JumpUp() void JumpDown(){ TurnLeft();TurnRight();Move(); TurnRight();TurnLeft();}

Instructions that repeat Karel often has to repeat instructions. For example, to run the hurdle race, the instruction AdvanceACorner() had to be repeated 8 times. There are three instructions built into Karel’s vocabulary that allow an instruction to be repeated. These are iterate, while, and do-while.

iterate iterate is used when it is necessary to have Karel perform an instruction a certain number of times. We previously handled this problem by writing the instruction as many times as needed. The new instruction has the following form:

iterate (iteration-amount) { } where iteration-amount is the number of times the statements in the loop body (statements between curly braces { }) will be performed.

For example, the solution of the hurdle race problem can now be written as one of the following: int main() int main() { { TurnOn(); TurnOn(); iterate (8) AdvanceACorner(); { AdvanceACorner(); AdvanceACorner(); AdvanceACorner(); } AdvanceACorner(); TurnOff(); AdvanceACorner(); } AdvanceACorner(); AdvanceACorner(); TurnOff(); }

Examples: void TurnRight() { iterate (3) { TurnLeft(); } The primitive instruction TurnLeft(); is repeated three times, which is equivalent to a right turn.

void Harvest1Row() { PickBeeper(); iterate (4) { Move(); PickBeeper(); } Karel would pick a single beeper and then repeat the sequence Move(); PickBeeper(); four times. The new instruction therefore would execute five PickBeeper() instructions and four Move() 's.

Curly braces are needed to mark the beginning and end of a loop body only if the body contains more than one statement. If the body consists of only one statement, the braces may (optionally) be omitted. Also, an ITERATE statement is considered a single statement. Original Code Code With Braces Omittedvoid TurnRight(){ iterate (3) iterate (3) { TurnLeft(); TurnLeft();} }

void TraverseSquare() { iterate (4)iterate(4) {{ iterate (5) iterate(5) { Move(); Move(); TurnLeft(); }} TurnLeft(); } } (NOTE: The iterate statement is NOT a standard C / C++ statement, although it can easily be simulated using the standard for statement. The iterate statement has been introduced to simplify Karel programming.)

while There are many situations where Karel needs to repeat an instruction but it is not yet known how often. For example, if we wish for Karel to pick up a pile of beepers of arbitrary size, he needs to repeatedly execute the PickBeeper() command, but because we do not know in advance the number of beepers in the pile, we do not know exactly how often to execute that command.

The WHILE statement is made-to-order for this situation: you can use it to tell Karel to repeat something while a certain predicate is true; for example to pick up beepers while there are any left to pick up. while (predicate) { } The predicate that appears between the parentheses of the WHILE statement comes from the same list of predicates that Karel can use in an IF statement.

Karel executes a WHILE by first checking the predicate. If the predicate is true, then the loop body is executed and Karel loops back to the predicate to check it again. This continues over and over as long as the predicate evaluates to true. If the predicate evaluates to false, Karel is finished with the WHILE statement and begins executing the instruction that immediately follows the WHILE statement.

NOTE: If the predicate is initially false the statement(s) in the loop body will not be executed at all. For this reason, WHILE loops are sometimes called zero-or-more times loops. Also note that, just as with ITERATE statements, curly braces are needed to mark the beginning and end of a loop body only if the body contains more than one statement.

Examples: void ClearCornerOfBeepers() { while (nextToABeeper) PickBeeper(); } Karel would pick up all beepers on the current corner, regardless how many there are (if it is a finite number, at least).

Building a WHILE Loop Step 1: Identify the one test that must be true when Karel is finished with the loop. In the above problem, Karel must pick all beepers on the corner. If we consider only tests that involve beepers, we can choose among four: anyBeepersInBeeperBag, noBeepersInBeeperBag, nextToABeeper, and notNextToABeeper Which one is the test we want?

Step 2: Use the opposite form of the test identified in step 1 as the loop predicate. This step implies that we should use nextToABeeper. The WHILE instruction continues to execute the loop body as long as the test is true and stops when it is false.

Step 3: Do whatever is required before or after the WHILE is executed to ensure we solve the given problem. In this example, we have to do nothing before or after the loop. However in other situations, we may miss one iteration of the loop and have to “clean things up,” which can be done either before or after the WHILE.

Step 4: Do the minimum that is needed to ensure that the test eventually evaluates to false so that the WHILE loop stops. Something within the body of the loop must allow the test eventually to evaluate to false or the loop will run forever. This implies that there must be some instruction (or sequence or instructions) within the loop that is related to the test. Thus in our example, since we are testing for nextToABeeper we must pick one (and only one) beeper somewhere in the loop.

Apply these four steps to a new problem. Karel is somewhere in the world facing south. One beeper is on every corner between Karel’s current position and the southern boundary wall. There is no beeper on the corner on which it is currently standing. Write a new instruction ClearAllBeepersToWall, to pick all the beepers. To solve any problem, ask questions: What do we know about Karel’s initial situation? Karel is facing south Karel is an unknown distance from the southern boundary wall Each corner between Karel and the southern boundary wall has one beeper.

Does any of this information provide insight toward a solution? Yes – Karel can travel forward until it reaches the southern boundary wall. It can pick a beeper from each corner as it travels. What Karel instruction can we use to keep Karel traveling southward until it reaches the southern boundary wall? Since traveling to the southern boundary wall requires an unknown number of move instructions, we can use a WHILE loop.

Four Step Process Step 1: Identify the one test that must be true when Karel is finished with the loop. Karel will be at the southern boundary wall, so the test frontIsBlocked will be true.

Step 2: Use the opposite form of the test identified in step 1. The opposite of frontIsBlocked is frontIsClear. Step 3: Do whatever is required before or after the WHILE is executed to ensure we solve the given problem. Since Karel is already facing south, we do not have to do anything.

Step 4: Do the minimum that is needed to ensure that the test eventually evaluates to false so that the WHILE loop stops. Karel must move forward one block then pick a beeper.

Based on this discussion, we can write the following new instruction: void ClearAllBeepersToWall() { while (frontIsClear) { Move(); PickBeeper(); }

A while loop can occur in a while loop: void PickBeepersToWall() { while (nextToABeeper) PickBeeper(); while (frontIsClear) { Move(); while (nextToABeeper) PickBeeper(); } The logic of these nested WHILE statements has Karel pick up all beepers between him and the wall ahead of him, including beepers on Karel's beginning street corner. Karel stops in front of the wall.

do While The DO...WHILE statement is not used a great deal. Nonetheless, there are occasional circumstances where we want to perform the body of a loop at least once and then check a predicate. The DO...WHILE statement allows us to do this. We call this construct a post-test or exit-controlled loop. do { } while (predicate);

The predicate that appears between the parentheses of the DO...WHILE statement comes from the same list of predicates that Karel can use in an IF statement. Karel executes a DO...WHILE by first executing the loop body. After completing the loop body, the predicate is checked. If the predicate is true then Karel loops back and executes the loop body again. This continues as long as the predicate evaluates to true. If the predicate evaluates to false, Karel is finished with the DO...WHILE statement and begins executing the instruction that immediately follows the DO...WHILE statement.

NOTE: Since the loop body is executed at least once, DO...WHILE loops are sometimes called one-or-more times loops. Also note that, just as with ITERATE statements, curly braces are needed to mark the beginning and end of a loop body only if the body contains more than one statement. However for this statement it is customary to always include the curly braces. Finally, note the need for a semicolon at the end of the statement.

void FaceWestIfFacingSouth() { if (facingSouth) { do { TurnLeft(); } while (notFacingWest); } If initially facing South, Karel will turn left until he is facing to the West.