Download
slide1 n.
Skip this Video
Loading SlideShow in 5 Seconds..
Introduction to Computer Science PowerPoint Presentation
Download Presentation
Introduction to Computer Science

Introduction to Computer Science

117 Vues Download Presentation
Télécharger la présentation

Introduction to Computer Science

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

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

  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. The while loop while ( condition )statement • 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

  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. Resulting Output DEGREES C DEGREES F -10.0 14.0 -9.0 15.8 -8.0 17.6 ... • 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

  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. How Do WeDivide It Up for Iteration? Before Loop • 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.” } Body ofLoop } Body ofLoop } Body ofLoop After Loop

  8. Program is Organized as Follows print first line of versewhile( 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. 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. The for loop • This is a very common kind of loop, where the variable is incremented each time through the loop 1. initialize 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.} 2. condition 3. increment So Java provides a special loop form that makes it easy to do: the for statement

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

  13. The for loop initialize condition increment for ( statement1; condition; statement2;)statement3 • This is exactly equivalent to writing the following while statement: statement1;while ( condition ) {statement3;statement2;}

  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. Comparison withOriginal 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);} initialize condition increment 1. initialize 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.} 2. condition 3. increment

  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. do-while Loops • Another form of loops in Java:dostatementwhile ( 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. In Other Words dostatementwhile ( condition ); • This is exactly equivalent to writing the following while statement: statementwhile ( condition ) statement;

  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. 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. Example: Reading Input in a Loop Enter score (eof ends the data): 85Enter score (eof ends the data): 62Enter score (eof ends the data): 93Enter score (eof ends the data): 87Enter score (eof ends the data): 51Enter score (eof ends the data): ^D or ^Z5 scores were entered.The average score was 75.6The maximum score was 93The minimum score was 51

  22. The Structure of the Problem Read a test scoreIf end of file, stop the loopProcess the test scoreRead a test scoreIf end of file, stop the loopProcess the test scoreRead a test scoreIf end of file, stop the loop…Process the test scoreRead a test scoreIf end of file, stop the loop

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

  24. Second Way ofGrouping the Iteration Read a test scoreIf end of file, stop the loopProcess the test scoreRead a test scoreIf end of file, stop the loopProcess the test scoreRead a test scoreIf end of file, stop the loop…Process the test scoreRead a test scoreIf end of file, stop the loop } do-while loop:test for end-of-file is at the end of each repeated section }

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

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

  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) { int trial; 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. So Our While Loop Looks Like This read scorewhile ( !sinp.eof( ) ) {process score read score}

  29. What the Processing Looks Like • We’ll have statements like:numberOfScores++; // how many scoressumOfScores = 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. 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. So far, what do we have? (partial) int numberOfScores = 0; int sumOfScores = 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. 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. 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. In Java Code • To maintain the truth of that invariant, we add the following to the loop:if (maxOfScores < score) //new largest score maxOfScores = score;if (minOfScores > 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) { int score; int sumOfScores = 0; int numberOfScores = 0; SimpleInput sinp = new SimpleInput(System.in); System.out.print(“Enter score (eof ends the data): “); score = sinp.readInt( ); int maxOfScores = score; int minOfScores = score; while ( !sinp.eof( ) ) { numberOfScores++; //new score sumOfScores = sumOfScores + score; //update sumif (maxOfScores < score) //new largest score maxOfScores = score; if (minOfScores > 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. 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. Example while ( condition1 ) {statement1if ( 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. The Loop-and-a-Half Problem • Before, we wrote the loop:read score while (! sinp.eof( ) ) {process scoreread score } • But what we really wanted was to executeread score process scoreas long as there are scores to process

  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. So we can use break • We might write it as follows:while (true) {read scoreif ( 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