Introduction to Computer Science Iteration –the while loop –the for loop Unit 8.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Solving Problems with Repetition. Objectives At the end of this topic, students should be able to: Correctly use a while statement in a C# program Correctly.
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.
Loops (Part 1) Computer Science Erwin High School Fall 2014.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
Introduction to Computer Science One Dimensional Arrays Unit 9.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Computer Programming 1 Repetition. Computer Programming 2 Objectives Repetition structures Study while and do loops Examine for loops A practical example.
© 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.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Loops and Iteration Chapter 5 Python for Informatics: Exploring Information
Chapter 6 Iteration Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E. Reingold.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
* What kind of loop would I use to complete the following: A. Output all of the prime numbers that are less than 100,000 B. Output the Fibonacci sequence.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Java Programming: From the Ground Up
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
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.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Introduction to Computer Science One Dimensional Arrays Unit 10.
Application development with Java Lecture 6 Rina Zviel-Girshin.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Flow of Control: Loops Module 4. Objectives Design a loop Use while, do, and for in a program Use the for-each with enumerations Use assertion checks.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Solving Problems with Repetition Version 1.0. Objectives At the end of this topic, students should be able to: Correctly use a while statement in a C#
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
BIL 104E Introduction to Scientific and Engineering Computing Lecture 6.
Introduction to Computers and Programming Lecture 10: For Loops Professor: Evan Korth New York University.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Introduction to Computer Science Iteration  the while loop  the for loop Assertions Unit 9.
UCT Department of Computer Science Computer Science 1015F Iteration
Introduction to Computer Science / Procedural – 67130
Chapter 5: Control Structures II
Repetition-Sentinel,Flag Loop/Do_While
Chapter 5: Control Structures II
LOOPS.
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
TOPIC 4: REPETITION CONTROL STRUCTURE
Outline Altering flow of control Boolean expressions
Control Statements Loops.
Control Statements Loops.
Control Statements:.
Presentation transcript:

Introduction to Computer Science Iteration –the while loop –the for loop Unit 8

8- 2 The while loop Just like in the robot world, Java needs mechanisms for repeating an action or group of actions while some condition is true (combination of looping and conditional checking) while ( condition ) statement

8- 3 The while loop Repeatedly execute statement while condition is true statement is called the body of the loop; can be a simple statement (as always, terminated by a ;) or a compound statement surrounded by { and } Can get us into an infinite loop while ( condition ) statement

class Temperature { // Print a table of corresponding C/F temperatures public static void main (String[ ] args) { final double LOW_TEMP = -10.0, HIGH_TEMP = 10.0; double cent,// The Centigrade temperature. fahr; // The Fahrenheit temperature. System.out.println(“DEGREES C\tDEGREES F“); cent = LOW_TEMP; while (cent <= HIGH_TEMP) { fahr = ( (9.0/5.0) * cent ) ;//Convert C to F System.out.println(“\t” + cent + “\t\t” + fahr); cent = cent + 1.0;//Increment the C value. } } }

8- 5 Resulting Output The \t is called an escape sequence; it represents the tab character, which it causes to be output (lining things up in columns) The entire {... } is executed each time, before the condition is checked again DEGREES CDEGREES F

8- 6 One More Simple Example Print out the following song: 10 in a bed and the little one said, “Roll over, roll over.” They all rolled over and one fell out, 9 in a bed and the little one said, “Roll over, roll over.” They all rolled over and one fell out, 8 in a bed and the little one said,... 1 in a bed and the little one said, “Alone at last.”

8- 7 How Do We Divide It Up for Iteration? One possible structure: 10 in a bed and the little one said, “Roll over, roll over.” They all rolled over and one fell out, 9 in a bed and the little one said, “Roll over, roll over.” They all rolled over and one fell out, 8 in a bed and the little one said,... 1 in a bed and the little one said, “Alone at last.” Before Loop } } } Body of Loop After Loop

8- 8 Program is Organized as Follows print first line of verse while ( more verses ) { print rest of verse print first line of next verse } print rest of last verse 10 in a bed and the little one said, “Roll over, roll over.” They all rolled over and one fell out, ??? in a bed and the little one said, “Alone at last.”

class TenInABed { // Print the nursery rhyme “Ten In a Bed.” static final int MAX_NUMBER_IN_BED = 10; public static void main (String[ ] args) { int numberInBed; System.out.println(MAX_NUMBER_IN_BED + “ in a bed and the little one said,”); numberInBed = MAX_NUMBER_IN_BED - 1; while (numberInBed > 0) { System.out.println(“\t\”Roll over, roll over.\””); System.out.println( “They all rolled over and one fell out,”); System.out.println( numberInBed + “ in a bed and the little one said,”); numberInBed = numberInBed - 1; } System.out.println(“\t\”Alone at last.\””); } }

8- 10 The for loop This is a very common kind of loop, where the variable is incremented each time through the loop cent = LOW_TEMP; while (cent <= HIGH_TEMP) { fahr = ( (9.0/5.0) * cent ) ;//Convert C to F System.out.println(“\t” + cent + “\t\t” + fahr); cent = cent + 1.0;//Increment the C value. } So Java provides a special loop form that makes it easy to do: the for statement

8- 11 The for loop This is a very common kind of loop, where the variable is incremented each time through the loop cent = LOW_TEMP; while (cent <= HIGH_TEMP) { fahr = ( (9.0/5.0) * cent ) ;//Convert C to F System.out.println(“\t” + cent + “\t\t” + fahr); cent = cent + 1.0;//Increment the C value. } So Java provides a special loop form that makes it easy to do: the for statement 1. initialize 2. condition 3. increment

8- 12 The for loop This is exactly equivalent to writing the following while statement: for ( statement1; condition; statement2; ) statement3 statement1; while ( condition ) { statement3; statement2; }

8- 13 The for loop This is exactly equivalent to writing the following while statement: for ( statement1; condition; statement2; ) statement3 statement1; while ( condition ) { statement3; statement2; } initializeconditionincrement

8- 14 Rewriting Our Temperature Loop for (cent = LOW_TEMP; cent <= HIGH_TEMP; cent =cent + 1.0;) { fahr = ( (9.0/5.0) * cent ) ;//Convert C to F System.out.println(“\t” + cent + “\t\t” + fahr); }

8- 15 Comparison with Original While Loop for (cent = LOW_TEMP; cent <= HIGH_TEMP; cent =cent + 1.0;) { fahr = ( (9.0/5.0) * cent ) ;//Convert C to F System.out.println(“\t” + cent + “\t\t” + fahr); } initializeconditionincrement cent = LOW_TEMP; while (cent <= HIGH_TEMP) { fahr = ( (9.0/5.0) * cent ) ;//Convert C to F System.out.println(“\t” + cent + “\t\t” + fahr); cent = cent + 1.0;//Increment the C value. } 1. initialize 2. condition 3. increment

8- 16 One Advantage It keeps all the loop controlling statements in one place, not spread throughout the loop For example, if we wanted to print the table in reverse order, all changes could be made at the top of the loop: for (cent = HIGH_TEMP; cent >= LOW_TEMP; cent =cent - 1.0;) { fahr = ( (9.0/5.0) * cent ) ;//Convert C to F System.out.println(“\t” + cent + “\t\t” + fahr); }

8- 17 do-while Loops Another form of loops in Java: do statement while ( condition ); The body of the loop is always executed at least once; the condition is checked after the body of the loop. This is basically a convenience.

8- 18 In Other Words This is exactly equivalent to writing the following while statement: do statement while ( condition ); statement while ( condition ) statement;

8- 19 Example: Count Number of Digits in an int numberOfDigits = 0; rest = number; while (rest > 0) { // The number of digits in number is numberOfDigits // plus the number of digits remaining in rest rest = rest / 10; numberOfDigits++; } What happens when number < 0? How do we fix it? What about when number = 0?

8- 20 One Solution: also works for number <= 0 numberOfDigits = 0; rest = number; do { // The number of digits in number is numberOfDigits // plus the number of digits remaining in rest rest = rest / 10; numberOfDigits++; } while (rest != 0) ; Loop is always executed once, even when the number = 0; notice the comment is unchanged.

8- 21 Example: Reading Input in a Loop Enter score (eof ends the data): 85 Enter score (eof ends the data): 62 Enter score (eof ends the data): 93 Enter score (eof ends the data): 87 Enter score (eof ends the data): 51 Enter score (eof ends the data): ^D or ^Z 5 scores were entered. The average score was 75.6 The maximum score was 93 The minimum score was 51

8- 22 The Structure of the Problem Read a test score If end of file, stop the loop Process the test score Read a test score If end of file, stop the loop Process the test score Read a test score If end of file, stop the loop … Process the test score Read a test score If end of file, stop the loop

8- 23 Two Ways of Grouping the Iteration: First Way Read a test score If end of file, stop the loop Process the test score Read a test score If end of file, stop the loop Process the test score Read a test score If end of file, stop the loop … Process the test score Read a test score If end of file, stop the loop } } while loop: test for end-of-file is at the beginning of each repeated section

8- 24 Second Way of Grouping the Iteration Read a test score If end of file, stop the loop Process the test score Read a test score If end of file, stop the loop Process the test score Read a test score If end of file, stop the loop … Process the test score Read a test score If end of file, stop the loop } } do-while loop: test for end-of-file is at the end of each repeated section

8- 25 Using the while Loop read score while ( not end of file ) { process score read score } Short, clear, natural

8- 26 Using the do-while Loop read score if ( not end of file ) do { process score read score } while ( not end of file ); Less natural

8- 27 Checking end-of-file We use the class for this course, creating a SimpleInput object and sending it the eof( ) message, which returns true or false import intro2cs.utils.*; class Readnumbers { public static void main (String[ ] args) { inttrial; SimpleInput sinp = new SimpleInput(System.in); System.out.print(“Type an integer: ”); trial = sinp.readInt(); if ( sinp.eof( ) ) System.out.print(“We’re at end of file.”); else … } }

8- 28 So Our While Loop Looks Like This read score while ( !sinp.eof( ) ) { process score read score }

8- 29 What the Processing Looks Like We’ll have statements like: numberOfScores++;// how many scores sumOfScores = sumOfScores + score; // update sum But for these variables numberOfScores and sumOfScores to be updated correctly within the loop, they need to be initialized correctly before the loop, to the value 0

8- 30 Loop Invariant A “loop invariant” is a statement that states the status of variables and their relationship during execution of the loop It is something that is supposed to be true every time we execute the loop (including the first time) We write it as a comment inside the loop

8- 31 So far, what do we have? (partial) intnumberOfScores = 0; intsumOfScores = 0; SimpleInput sinp = new SimpleInput(System.in); System.out.print(“Enter score (eof ends the data): “); score = sinp.readInt( ); while ( !sinp.eof( ) ) { numberOfScores++;//new score sumOfScores = sumOfScores + score; //update sum // numberOfScores is the number of scores read // so far and sumOfScores is their sum System.out.print(“Enter score (eof ends the data): “); score = sinp.readInt( ); }

8- 32 Afterwards Once the loop has ended, we can compute the average score simply as follows: (double) sumOfScores / numberOfScores Why do we need to cast sumOfScores to a double? What do we need to check before we do this computation?

8- 33 What About Maximum and Minimum Scores? Consider how the invariant could be changed to reflect the fact that, in addition to numberOfScores and sumOfScores, we also have maxOfScores and minOfScores: // The numberOfScores is the number // of scores read so far and sumOfScores is // their sum; maxOfScores is the largest // score and minOfScores is the smallest // score read so far

8- 34 In Java Code To maintain the truth of that invariant, we add the following to the loop: if (maxOfScores score) // new smallest score minOfScores = score; We must also initialize these two new variables, so the invariant is always true. We initialize them to the first score read.

public static void main (String[ ] args) { intscore; intsumOfScores = 0; intnumberOfScores = 0; SimpleInput sinp = new SimpleInput(System.in); System.out.print(“Enter score (eof ends the data): “); score = sinp.readInt( ); intmaxOfScores = score; intminOfScores = score; while ( !sinp.eof( ) ) { numberOfScores++;//new score sumOfScores = sumOfScores + score; //update sum if (maxOfScores score) //new smallest score minOfScores = score; // numberOfScores is the number of scores read // so far and sumOfScores is their sum; maxOfScores is // the largest score and minOfScores is the smallest // score read so far System.out.print(“Enter score (eof ends the data): “); score = sinp.readInt( ); } … etc…

8- 36 The break Statement in Loops We saw the break statement before, in switch statements They can also be used to terminate the execution of while and for loops When a break is encountered during the execution of one of these loops, the loop ends immediately, and execution continues with the statement following the loop

8- 37 Example while ( condition1 ) { statement1 if ( condition2 ) break; statement2 } With this use of the break statement, we can jump out of the loop in the middle. When is this useful?

8- 38 The Loop-and-a-Half Problem Before, we wrote the loop: read score while (! sinp.eof( ) ) { process score read score } But what we really wanted was to execute read score process score as long as there are scores to process

8- 39 But we had to read score to find out that there were no more scores How about this? while (true) { read score process score } Doing this an extra “half time”, quitting in the middle when read score fails (i.e., we hit end of file)

8- 40 So we can use break We might write it as follows: while (true) { read score if ( sinp.eof( ) ) break; process score } That way, the “read” part of the “read- process” loop doesn’t get written down twice, before the loop and during the loop