Java Loops (Java: An Eventful Approach, Ch 7 and 13), Slides Credit: Bruce, Danyluk and Murtagh CS 120 Lecture 16 6 November 2012.

Slides:



Advertisements
Similar presentations
Overloading Having more than one method with the same name is known as overloading. Overloading is legal in Java as long as each version takes different.
Advertisements

Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.
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.
Computer Science 1620 Loops.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
IAT 800 Lab 1: Loops, Animation, and Simple User Interaction.
1 Parts of a Loop (reminder) Every loop will always contain three main elements: –Priming: initialize your variables. –Testing: test against some known.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Chapter 5: Control Structures II (Repetition)
Programs Involving Repetition Drawing Grass Drawing grids Printing marks on a ruler Repeatedly rolling dice in craps game.
CS 106 Introduction to Computer Science I 02 / 11 / 2008 Instructor: Michael Eckmann.
Loops – While, Do, For Repetition Statements Introduction to Arrays
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Loops II Lecture 13, Thu Feb
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Recognizing Patterns Counting: continually updating a value by a fixed amount Counting raindrops int dropCount = 0; //Raindrop counter while (dropCount.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
CS 106 Introduction to Computer Science I 09 / 28 / 2007 Instructor: Michael Eckmann.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
TODAY’S LECTURE Review Chapter 2 Go over exercises.
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”);
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Java Programming: From the Ground Up
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
CPS120 Introduction to Computer Science Iteration (Looping)
REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.
Loops and Iteration for Statements, while Statements and do-while Statements.
Conditional Execution
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.
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Repetition Structures Repetition Structures allow you to write programs that will repeat program steps multiple times. –Also called Loops –Counter controlled.
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Conditional Statements Consider: if the mouse location is contained in the rectangle, display message “success” Some programming constructs can choose.
Java Decision Making and booleans (Java: An Eventful Approach, Ch 4), Slides Credit: Bruce, Danyluk and Murtagh CS 120 Lecture October 2012.
Recognizing Patterns Counting: continually updating a value by a fixed amount Counting raindrops int dropCount = 0; //Raindrop counter while (dropCount.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
CPS120 Introduction to Computer Science Iteration (Looping)
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
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.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 5: Looping. Using the while Loop Loop – A structure that allows repeated execution of a block of statements Loop body – A block of statements.
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
Lecture 4b Repeating With Loops
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
Introduction To Repetition The for loop
Loop Structures.
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Java Programming: Guided Learning with Early Objects
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Programs Involving Repetition
Chapter 6: Repetition Statements
Loop Strategies Repetition Playbook.
Building Java Programs
Loops and Iteration CS 21a: Introduction to Computing I
Lec 17 Using Nested Loops and Objects in an Applet Class
Looping and Repetition
Presentation transcript:

Java Loops (Java: An Eventful Approach, Ch 7 and 13), Slides Credit: Bruce, Danyluk and Murtagh CS 120 Lecture 16 6 November 2012

Programs Involving Repetition Drawing Grass Drawing grids Printing marks on a ruler Repeatedly rolling dice in craps game

public void begin() { // add the blades of grass new Line(0, GRASS_TOP, 0, GROUND_LINE, canvas); new Line(4, GRASS_TOP, 4, GROUND_LINE, canvas); new Line(8, GRASS_TOP, 8, GROUND_LINE, canvas); new Line(12, GRASS_TOP, 12, GROUND_LINE, canvas); new Line(16, GRASS_TOP, 16, GROUND_LINE, canvas); … } Recognizing a Pattern

Making a Pattern Explicit // add the blades of grass bladePosition = 0; new Line(bladePosition, GRASS_TOP, bladePosition, GROUND_LINE, canvas); bladePosition = bladePosition + GRASS_SPACING; new Line(bladePosition, GRASS_TOP, bladePosition, GROUND_LINE, canvas); bladePosition = bladePosition + GRASS_SPACING; new Line(bladePosition, GRASS_TOP, bladePosition, GROUND_LINE, canvas); bladePosition = bladePosition + GRASS_SPACING; …

Eliminating Code Repetition private int bladePosition=0; public void onMouseClick(Location point) { // grow a blade of grass with each mouse click if (bladePosition < canvas.getWidth()) { new Line(bladePosition, GRASS_TOP, bladePosition, GROUND_LINE, canvas); bladePosition = bladePosition + GRASS_SPACING; } First approach tedious for programmer Second approach tedious for user

The while Loop (Indefinite loop) A control construct for specifying repetition General Structure: while (condition) { //Statements to be repeated }

Drawing Grass with while public void begin() { // add the blades of grass double bladePosition = 0; while ( bladePosition < canvas.getWidth() ) { new Line(bladePosition,GRASS_TOP, bladePosition,GROUND_LINE, canvas); bladePosition = bladePosition + GRASS_SPACING; }

while (verticalCorner.getX() < canvas.getWidth() || horizontalCorner.getY() < canvas.getHeight() ) { new FilledRect(verticalCorner, 5, canvas.getHeight(), canvas); new FilledRect(horizontalCorner, canvas.getWidth(), 5, canvas); verticalCorner.translate(10, 0); horizontalCorner.translate(0, 10); } Drawing a Grid

The Counting while loop Counting up int i=initialValue; while(i<endValue){ //statements to be repeated i++; }

Drawing a Number of Bricks Might want to draw exactly 10 bricks private static final int BRICKS_TOTAL=10; int brickPosition=0; int brickCount=0; while ( brickCount < BRICKS_TOTAL ) { new FilledRect(brickPosition, BRICK_TOP, BRICK_WIDTH, BRICK_HEIGHT, canvas); brickPosition = brickPosition + BRICK_WIDTH + BRICK_SPACING; brickCount++; }

Suppose we want to draw a brick wall

Use a while loop to draw each row of the wall int level = 0; while ( level < WALL_HEIGHT) { …//draw one row of bricks brickY = brickY + BRICK_HEIGHT; level ++; }

Already know how to draw a row of bricks Nest 1 while loop inside another while (condition1) { //moves to draw a row of bricks while (condition2) { //draws one row of bricks }

Putting Things Together int level = 0; double brickY = WALL_Y; while ( level < WALL_HEIGHT ) { brickInLevel = 0; brickX = WALL_X; //draw one row of bricks while ( brickInLevel < WALL_WIDTH ) { new FilledRect ( brickX, brickY, BRICK_WIDTH, BRICK_HEIGHT, canvas); brickX = brickX + BRICK_WIDTH+1; brickInLevel ++; } brickY = brickY – BRICK_HEIGHT-1; level ++; }

Making Code Simple and Clear No if ( box.contains(point)) { //do nothing } else { counter ++; } Yes If ( !box.contains (point) ) { counter++; } Avoid empty if-parts

if ( box.contains (point) ) { boxGrabbed = true; } else { boxGrabbed = false; } if ( boxGrabbed == true ) { … } boxGrabbed = box.contains.(point); if (boxGrabbed) { … } Use Boolean expressions in assignments Don’t use true or false in conditionals

Simplifying Code with DeMorgan’s Laws DeMorgan’s Laws ! ( A && B ) = !A || !B ! ( A || B ) = !A && !B

Applying DeMorgan’s Laws Simplify: !( x = 100 ) using !( A || B ) = !A && !B !( x = 100 ) ( x >= 0 ) && ( x < 100 )

Curly Braces Curly braces bracketing multiple lines of code are necessary if ( targetContains(pt) ) { if ( targetContains (pt) ) target.hide(); target.hide(); score++; score++; } In the second version, score is updated despite the conditional

Curly Braces A single line of code runs the same with and without curly braces if ( temperature >= 100 ) { display.setText("Water is in a gaseous phase"); } is the same as if ( temperature >= 100 ) display.setText("Water is in a gaseous phase");

Curly Braces Which interpretation is correct? if ( temperature >= 80 ) if (raining) display.setText(“Bring an Umbrella"); else display.setText(“T-shirt Weather"); if ( temperature >= 80 ) if (raining) display.setText(“Bring an Umbrella"); else // WRONG!! This else matches the nearest if display.setText(“Bring a coat!"); This is called the “Dangling else” problem.

Recognizing Patterns Counting: continually updating a value by a fixed amount Counting raindrops int dropCount = 0; //Raindrop counter while (dropCount < MAX) { new Raindrop( … ); dropCount++; }

Counting Bricks while ( count < TOTAL ) { new Brick(…); count++; }

The Counting while Loop int i = initialValue;// initialize while (i < stopVal) { // test... // do stuff i++; // increment } “Counter-Controlled Loop Pattern”

The for loop (Definite Loop) Especially useful for counting Ex: for ( int i=initialVal; //initialize i<stopVal; //test i++;) {//increment …//do stuff }

Counting Raindrops with for Loop for (int dropCount = 0; dropCount <MAX; dropCount++) { new Raindrop ( … ); }

More General Start and End Points Loops can take whatever starting point, end point, and increment Ex: for (int i=23; i <= 1728; i=i+591;){ //do stuff } But one should avoid using a double for any of the three values

Counting Backwards with for Loop Ex: Printing a countdown for (int count = 10; count >= 1; count--) { System.out.println(count); }

Update Values Can increment loop index by any value Ex: Drawing grass blades for (int pos = 0; pos < WIDTH; pos = pos + GAP) { new Line (pos, TOP, pos, GROUND, canvas); }

General Syntax of for Loop for (initialization; condition; update) { //Do something } Initialization: gen’ly creates a counting variable Condition: a boolean expression to stop the loop Updating: updates the variable created

Nested Loops Any loop body can contain another loop Ex: for ( … ) { while (…) { for(…) { }

The do while Loop Syntax: do { } while ( ) (see Craps Example online)

do while Loop vs while Loop do while –Condition checked at the end –Loop body executed at least once while –Condition checked at the beginning –Loop body may never execute

Avoiding Loop Errors Easier to find errors if you know where to look Common loop errors include: Off by 1 in counting loops Infinite loops

Off by one errors Suppose we want to run a for loop 5 times: The left hand version will run it 6 times, not 5. for(int i=0;i<=5; i++){ } for(int i=0;i<5;i++) { }

Infinite Loops Ex: while ( count< TOTAL ) { new Brick (…); } Since value of count is not updated, the condition in while will stay true forever.

Student To Do’s HW07 –Exercise (DNA Generator) –Exercise (Morse Code) –Due Monday 11/12 by 11:59pm Read Java: An Eventful Approach –Ch. 7 and 13 (Today) 37