Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Introduction to Computer Science Iteration –the while loop –the for loop Unit 8."— Presentation transcript:

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

2 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

3 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

4 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 ) + 32.0;//Convert C to F System.out.println(“\t” + cent + “\t\t” + fahr); cent = cent + 1.0;//Increment the C value. } } }

5 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 -10.014.0 -9.015.8 -8.017.6...

6 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.”

7 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- 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.”

9 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.\””); } }

10 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 ) + 32.0;//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

11 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 ) + 32.0;//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

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

13 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

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

15 8- 15 Comparison with Original While Loop for (cent = LOW_TEMP; cent <= HIGH_TEMP; cent =cent + 1.0;) { fahr = ( (9.0/5.0) * cent ) + 32.0;//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 ) + 32.0;//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

16 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 ) + 32.0;//Convert C to F System.out.println(“\t” + cent + “\t\t” + fahr); }

17 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.

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

19 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?

20 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.

21 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

22 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

23 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

24 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

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

26 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

27 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 … } }

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

29 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

30 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

31 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( ); }

32 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?

33 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

34 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.

35 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…

36 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

37 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?

38 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

39 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)

40 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


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

Similar presentations


Ads by Google