Karel – Chapter 6 Instructions That Repeat

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Repetition Statements Perform the same task repeatedly Allow the computer to do the tedious, boring things.
Programming In C++ Spring Semester 2013 Lecture 3 Programming In C++, Lecture 3 By Umer Rana.
Karel J Robot Chapter 6.
Do-while Loops Programming. COMP102 Prog Fundamentals I: do-while Loops /Slide 2 The do-while Statement l Syntax do action while (condition) l How it.
Loops –Do while Do While Reading for this Lecture, L&L, 5.7.
CHAPTER 5: Repetition Control Structure. Objectives  To develop algorithms that use DOWHILE and REPEAT.. UNTIL structures  Introduce a pseudocode for.
Computer Science 1620 Loops.
1 Lecture 11:Control Structures II (Repetition) (cont.) Introduction to Computer Science Spring 2006.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
Chapter 2: Algorithm Discovery and Design
Chapter 5: Control Structures II (Repetition)
1 Lecture 14 Chapter 6 Looping Dale/Weems/Headington.
Looping Yong Choi School of Business CSU, Bakersfield.
Week 11 Recap CSE 115 Spring Want to write a programming language? You’ll need three things: You’ll need three things: –Sequencing –Selection Polymorphism.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
Copyright © Texas Education Agency, Computer Programming For Loops.
New Mexico Computer Science For All More Looping in NetLogo Maureen Psaila-Dombrowski.
1 karel_part5_loops Iteration (Loops) Loops repeat a set of instructions Two types of loops: –Definite loops ( for ) perform instructions explicit (known)
Lecture Set 5 Control Structures Part D - Repetition with Loops.
Chapter 5 Control Structures: Loops 5.1 The while Loop The while loop is probably the most frequently used loop construct. The while loop is a conditional.
CPS120 Introduction to Computer Science Iteration (Looping)
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
Chapter 4 Loops Write code that prints out the numbers Very often, we want to repeat a (group of) statement(s). In C++, we have 3 major ways of.
1 Karel – Chapter 6 Instructions That Repeat Note: Original slides provided by and modified for Mr. Smith’s AP Computer Science.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (for) Outline 4.1Introduction 4.2The.
1 Ch. 6 Iteration (Loops) Loops repeat a set of instructions Two types of loops: –Definite loops ( for ) perform instructions explicit number of times.
CPSC1301 Computer Science 1 Chapter 4 Manipulating Pictures, Arrays, and Loops part 5.
CPS120 Introduction to Computer Science Iteration (Looping)
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
Chapter 6 Questions Quick Quiz
Repetition Control Structure. Introduction Many applications require certain operations to be carried out more than once. Such situations require repetition.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
Karel J. Robot Chapter 6 Instructions That Repeat.
Chapter 7: Repetition Structure (Loop) Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills.
1 Karel – Chapter 6 Instructions That Repeat Note: Original slides provided by and modified for Mr. Smith’s AP Computer Science.
Loops Tonga Institute of Higher Education. Introduction Programs need to be able to execute tasks repeatedly. Use loops to repeat actions  For Loop 
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
Karel J. Robot Chapter 6 Instructions That Repeat.
CHAPTER 4 REPETITION STRUCTURES 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Asma Alosaimi.
Follow up from lab See Magic8Ball.java Issues that you ran into.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 10P. 1Winter Quarter Repetition Structures Lecture 10.
Topic : While, For, Do-While Loop Guided By : Branch : Batch :
Slides by Evan Gallagher
Slides by Evan Gallagher
Chapter 4 Repetition Statements (loops)
Lecture 7: Repeating a Known Number of Times
Karel J Robot Chapter 6.
Chapter 4 Repetition Structures
Chapter 4 Repetition Structures
Iteration with While You can say that again.
Debugging October 3, 2007 ComS 207: Programming I (in Java)
CPS120: Introduction to Computer Science
Introduction to pseudocode
Lecture Notes – Week 3 Lecture-2
Repetition Control Structure
Debugging October 4, 2006 ComS 207: Programming I (in Java)
Seating “chart” Front - Screen rows Back DOOR.
FLUENCY WITH INFORMATION TECNOLOGY
Introduction to Computer Science
Repetition Statements (Loops) - 2
PROGRAM FLOWCHART Iteration Statements.
Statements in C Programming
Iteration (Loops) Loops repeat a set of instructions
Types of loops definite loop: A loop that executes a known number of times. Examples: Repeat these statements 10 times. Repeat these statements k times.
JavaScript 101 Lesson 8: Loops.
Looping and Repetition
Presentation transcript:

Karel – Chapter 6 Instructions That Repeat Note: Original slides provided by www.apComputerScience.com and modified for Mr. Smith’s AP Computer Science A class

Iteration Graphic Organizer Control structures Methods Sequential Iteration Conditional Types of control structures Types of loops Java statement Syntax Examples:

Iteration (Loops) Loops repeat a set of instructions Two types of loops: Definite loops ( for loops ) perform instructions an explicit number of times Indefinite loops ( while loops ) perform instructions an indefinite number of times (until a certain test fails)

Definite vs. Indefinite Loop? A new class you’re writing has a method with the following signature: public void move (int numMoves) Should it be implemented with a definite loop or an indefinite loop? Justify your answer. Could it be implemented with the other type of loop? If so, should we? Is it a good idea or bad idea? - should use a definite loop (for) - we know in advance exactly how many times (numMoves number of times) that we should move - therefore, definite - yes, we could use an indefinite loop - the loops are always interchangable - that doesn’t mean we should use whatever we feel like - I can, for example, use a sledge hammer to pound in a thumb tack - but it’s not the right tool. recognize patterns in cs and solve using a standard technique/tool. ok - i’ve heard the argument that always using a for loop is good because your initialization/increment/test are all located in one location (namely, between the parentheses). fine. i see merit. but, for now - in the beginning - i teach patterns. later, i change my mind and do things like: for (Iterator iter=someArrayList.iterator(); iter.hasNext(); )

Iteration Graphic Organizer Control structures Methods Sequential Iteration Conditional Types of control structures Definite Loops Types of loops Indefinite Loops for Java statement while Syntax Examples:

for Loops General syntax: for ( <initialize variable>; <test>; <increment> ) { <instruction set> }

for Loops (cont.) <initialize variable> sets a variable/identifier to a certain value (variable is usually count, i, j) <test> is a test that is evaluated each time the body is about to be executed (when false, the loop is exited) <increment> changes the loop control variable (usually i++ or i--). The incrementing is done at the bottom of the loop. i++ means “add 1 to i”. i-- means “subtract 1 from i”.

for Loops (cont.) Example: for (int i=1; i<=3; i++) { move(); putBeeper(); } This causes the robot to move and place a beeper down on 3 different corners Note: Write this on the board so that we can refer to it on next slide

for Loops (cont.) Flow of for loops: Initialization statement executes If test is true, proceed to next step; if test is false, go to step 6 Instructions in body of loop are executed Increment statement executes Return to step 2 Program proceeds to statements after loop

Iteration Graphic Organizer Control structures Methods Sequential Iteration Conditional Types of control structures Definite Loops Types of loops Indefinite Loops for Java statement while initialize variable test increment Syntax Examples: for ( int i=1; i<=3; i++ ) { move(); putBeeper(); }

Move a specified number of times Example: public void move (int numMoves) { for (int i=1; ___________; i++) super.move(); } This causes the robot to move a specified number of times for (int i=1; i<=numMoves; i++)

Try this yourself Write a for loop to pick up a beeper (if there is one) on the four street corners directly in front of the robot: for (int i=1; i<=4; i++) { move(); if ( nextToABeeper() ) pickBeeper(); }

BeeperSquare Exercise

BeeperSquare Exercise Create a BeeperSquare robot class that extends SmartBot or Robot (you may want to use some of its methods) Create a method named drawSquare() that uses at least one “for” loop (two “for” loops would be better) that will create a square with 6 beepers on each side. Use a single robot to do this. The end result should be a square containing 20 beepers (only one beeper on each street corner). Create a client program that will test this new class. Try constructing two robots and drawing 2 separate squares in the world (overlapping the two).

while Loop Situation Team up with your neighbor for a couple minutes and discuss a situation that would necessitate that you use a while (indefinite) loop to solve the problem Note: We might use one or two of these as examples later on when we are discussing while loops.

while Loops General form: while ( <test> ) { <instruction list> } Loop continues until test is false

while Loops (cont.) Example: while (frontIsClear()) { move(); } Causes the robot to move continuously until there is a wall in front of it

while Loops (cont.) Flow of while loops: If test is true, proceed to step 2; if test is false, go to step 4 Instructions in body of loop are executed Go to step 1 Statements after loop are executed

Iteration Graphic Organizer Control structures Methods Sequential Iteration Conditional Types of control structures Definite Loops Types of loops Indefinite Loops for Java statement while initialize variable test increment Syntax test Examples: for ( int i=1; i<=3; i++ ) { move(); putBeeper(); } while ( frontIsClear() ) { move(); }

Building a While Loop The following is a more systematic way of creating while loops. This will be extremely helpful to you at various times in the course and on the AP exam. Example: the robot moves until it comes to a beeper and then picks it up Step 1 – Identify what is true when the loop is finished (this is always easier than determining what is false while it is still executing) Step 2 – Use the opposite form of step 1’s result as the <test> for the loop. You just need to negate the entire thing. (note: Now and again you might find that “DeMorgan-izing” your result is helpful when answering AP-like questions.) Step 3 – make progress toward the goal (completion of the loop) within the loop nextToABeeper() while ( ! nextToABeeper() ) move();

Building a while Loop (cont’d) Step 4 – Do whatever is required before and/or after the loop to ensure that we solve the given problem Putting it all together using this 4-step approach: while ( ! nextToABeeper() ) { move(); } pickBeeper(); Another Example: Pick all beepers from a corner without knowing how many there are. pickBeeper();

while Loop Exercise Back on an earlier slide, you drew up a situation that would best be solved using a while loop - now write the code to solve your problem If you did not come up with a problem, use the following situation: The robot should lay down a single beeper on each street corner in a straight line in the direction it is facing until it comes to a wall. In this case it should stop and turn off. To test this, create a robot on street corner (4, 8) which is facing west, and has 10 beepers in its beeper bag.

DeMorgan’s Law De Morgan's laws are rules relating the logical operators “and" and “or" in terms of each other via negation. In another form: NOT (a AND b) = (NOT a) OR (NOT b) NOT (a OR b) = (NOT a) AND (NOT b) In java, this corresponds to: ! (a && b) is the same as !a || !b ! (a || b) is the same as !a && !b

DeMorgan’s Law Useful in Step 2 for negating the end situation We want to loop until a wall is in front AND a beeper is on the current corner ! frontIsClear() && nextToABeeper() Use DeMorgan’s Law to negate this. Negate the two predicates and replace && with || : while ( frontIsClear || !nextToABeeper() )

Let’s build a while loop Move a robot until it is not on a corner with any other robots and there is a wall on the left, then pick up the beeper that will be waiting there (the “hard” part is getting the condition correct without using a trial-and-error method – you don’t get to run any programs during our tests nor on the AP exam – also, you’ll code your labs faster if you have a way to ensure correct conditions EVERY time – without the crutch of running your code) You may use && and || for this exercise. Use the 4-step process now… while (???) { ??? }

You try the while condition What is true when the loop is finished? !nextToARobot() && !leftIsClear() Use the opposite form of step 1’s result as the <test> for the loop while (nextToARobot() || leftIsClear()) Make progress toward the goal within loop move(); Do whatever is required before and/or after the loop to ensure that we solve the given problem pickBeeper();

You try the while condition You may use && and || for this Write a loop that moves a robot forward until it is either next to a robot, next to a beeper, or there is no wall on its right while ( ??? ) { ??? }

You try the while condition What is true when the loop is finished? nextToARobot() || nextToABeeper() || rightIsClear() Use the opposite form of step 1’s result as the <test> for the loop while (!nextToARobot() && !nextToABeeper() && !rightIsClear()) Make progress toward the goal within loop move(); Do whatever is required before and/or after the loop to ensure that we solve the given problem Nothing required

Fence Post Problem This is a situation where we must perform some (but not all) of the statements in the loop either before or after the loop to solve the given problem. This is because the instructions in the loop do not entirely solve the problem for either the first time through the loop or the last time through the loop. This is called the Fence Post Problem because if we order 3 fence sections, we actually need 4 fence posts. What if we have five beepers in a row. The robot starts on the same corner as the first beeper. It needs to pick up all 5 beepers and it needs to end up at the corner of the last beeper. How would we go about doing this? for (int i=1; i<=4; i++) { pickBeeper(); move(); }

Fence Post Problem move() move() move() move() pickBeeper()

Infinite Loops In a for or while loop, it is possible for the test to never be false When this happens, the loop continues infinitely Depending on the compiler, application, and other circumstances, an error may occur or the app may crash with a memory error