Introduction to Computer Science Unit 9 l Iteration



































![public static void main (String[ ] args) { int score; int sum. Of. Scores public static void main (String[ ] args) { int score; int sum. Of. Scores](https://slidetodoc.com/presentation_image_h2/97535d3eba6011bfbdcb4272518ca2d0/image-36.jpg)





















- Slides: 57
Introduction to Computer Science Unit 9 l Iteration the while loop u the for loop u l Assertions
The while loop l 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 9 - 2
The while loop while (condition) statement l Repeatedly execute statement while condition is true l 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 } l Can get us into an infinite loop 9 - 3
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; cent, // The Centigrade temperature fahr; // The Fahrenheit temperature System. out. println("DEGREES Ct. DEGREES 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 + "tt" + fahr); cent++; //Increment the C value } } }
Resulting Output DEGREES C -10. 0 -9. 0 -8. 0. . . DEGREES F 14. 0 15. 8 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) l The entire body of the loop {. . . } is executed each time, before the condition is checked again l 9 - 5
One More Simple Example l 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. " 9 - 6
How Do We Divide It Up for Iteration? l One possible structure: 10 in a bed and the little one said, Before Loop "Roll over, roll over. " of They all rolled over and one fell out, Body Loop 9 in a bed and the little one said, "Roll over, roll over. " Body of They all rolled over and one fell out, Loop 8 in a bed and the little one said, . . . Body of Loop 1 in a bed and the little one said, After Loop "Alone at last. " } } } 9 - 7
Program is Organized as Follows print first line of verse 10 in a bed and the little one said, while ( more verses ) { “Roll over, roll over. ” print rest of verse They all rolled over and one fell out, print first line of next verse ? ? ? in a bed and the little one said, } print rest of last verse “Alone at last. ” 9 - 8
class Ten. In. ABed { // Print the nursery rhyme “Ten In a Bed. ” static final int MAX_NUMBER_IN_BED = 10; public static void main (String[ ] args) int { number. In. Bed = MAX_NUMBER_IN_BED - 1; System. out. println(MAX_NUMBER_IN_BED + " in a bed and the little one said, "); while (number. In. Bed > 0) { System. out. println("t"Roll over, roll over. ""); System. out. println( "They all rolled over and one fell out, "); System. out. println( number. In. Bed + " in a bed and the little one said, "); number. In. Bed--; } System. out. println("t"Alone at last. ""); } }
A while Bug // An empty statement bug System. out. println("Enter a positive number. "); Simple. Input. in. read. Int(Number); while (Number <= 0) ; //This semicolon //shouldn't be here Simple. Input. in. read. Int(Number); System. out. println("Thank you. "); Causes an infinite loop. 9 - 10
The for loop l 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 + "tt" + fahr); cent++; //Increment the C value. } So Java provides a special loop form that makes it easy to do: the for statement 9 - 11
The for loop This is a very common kind of loop, where the variable is incremented each time through the loop 1. cent initialize = LOW_TEMP; 2. condition l while (cent <= HIGH_TEMP) { fahr = ( (9. 0/5. 0) * cent ) + 32. 0; //Convert C to F System. out. println("t" + cent + "tt" + fahr); cent++; //Increment the C value. } 3. increment So Java provides a special loop form that makes it easy to do: the for statement 9 - 12
The for loop for ( statement 1; condition; statement 2 ) statement 3; l This is exactly equivalent to writing the following while statement: statement 1; while ( condition ) { statement 3; statement 2; } 9 - 13
The for loop initialize condition increment for ( statement 1; condition; statement 2 ) statement 3 l This is exactly equivalent to writing the following while statement: statement 1; while ( condition ) { statement 3; statement 2; } 9 - 14
Rewriting Our Temperature Loop for (cent = LOW_TEMP; cent <= HIGH_TEMP; cent++) { fahr = ( (9. 0/5. 0) * cent ) + 32. 0; //Convert C to F System. out. println("t" + cent + "tt" + fahr); } 9 - 15
Comparison with Original While Loop initialize condition increment for (cent = LOW_TEMP; cent <= HIGH_TEMP; cent++) { fahr = ( (9. 0/5. 0) * cent ) + 32. 0; //Convert C to F System. out. println("t" + cent + "tt" + fahr); } 1. initialize cent = LOW_TEMP; 2. condition while (cent <= HIGH_TEMP) { fahr = ( (9. 0/5. 0) * cent ) + 32. 0; //Convert C to F System. out. println("t" + cent + "tt" + fahr); cent++; //Increment the C value. } 3. increment 9 - 16
One Advantage It keeps all the loop controlling statements in one place, not spread throughout the loop l For example, if we wanted to print the table in reverse order, all changes could be made at the top of the loop: l for (cent = HIGH_TEMP; cent >= LOW_TEMP; cent--) { fahr = ( (9. 0/5. 0) * cent ) + 32. 0; //Convert C to F System. out. println("t" + cent + "tt" + fahr); } 9 - 17
do-while Loops l 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. 9 - 18
In Other Words do statement while ( condition ); l This is exactly equivalent to writing the following while statement: statement while ( condition ) statement; 9 - 19
Example: Count Number of Digits in an int number. Of. Digits = 0; rest = number; while (rest > 0) { // The number of digits in number is number. Of. Digits // plus the number of digits remaining in rest = rest / 10; number. Of. Digits++; } • What happens when number < 0? • How do we fix it? • What about when number == 0? 9 - 20
One Solution: also works for number <= 0 number. Of. Digits = 0; rest = number; do { // The number of digits in number is number. Of. Digits // plus the number of digits remaining in rest = rest / 10; number. Of. Digits++; } while (rest != 0) ; Loop is always executed once, even when the number == 0; notice the comment is unchanged. 9 - 21
Example: Reading Input in a Loop Enter score (eof ends the data): Enter score (eof ends the data): 85 62 93 87 51 ^D or ^Z 5 scores were entered. The average score was 75. 6 The maximum score was 93 The minimum score was 51 9 - 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 9 - 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 } } while loop: test for end-of-file is at the beginning of each repeated section 9 - 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 } } do-while loop: test for end-of-file is at the end of each repeated section 9 - 25
Using the while Loop read score while ( not end of file ) { process score read score } Short, clear, natural 9 - 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 9 - 27
Checking end-of-file l We have a function, Simple. Input. in. eof( ), which returns true or false (if we’re at the end of the file, or not) import intro 2 cs. utils. *; class Readnumbers { public static void main (String[ ] args) int throws IOException { trial; System. out. print("Type an integer: "); trial = Simple. Input. in. read. Int(); if (Simple. Input. in. eof( ) ) System. out. print("We're at end of file. "); else … } } 9 - 28
So Our While Loop Looks Like This read score while (!Simple. Input. in. eof( )) { process score read score } 9 - 29
What the Processing Looks Like l We’ll have statements like: number. Of. Scores++; // how many scores sum. Of. Scores += score; //update sum (same as // sum. Of. Scores = sum. Of. Scores + score l But for these variables number. Of. Scores and sum. Of. Scores to be updated correctly within the loop, they need to be initialized correctly before the loop, to the value 0 9 - 30
Loop Invariant l. A “loop invariant” is a statement that states the status of variables and their relationship during execution of the loop l It is something that is supposed to be true every time we execute the loop (including the first time) l We now write it as a comment inside the loop, but will soon learn another way… 9 - 31
So far, what do we have? (partial) int number. Of. Scores = 0; sum. Of. Scores = 0; System. out. print("Enter score (eof ends the data): "); score = Simple. Input. in. read. Int( ); while ( !Simple. Input. in. eof( ) ) { number. Of. Scores++; //new score sum. Of. Scores += score; //update sum // number. Of. Scores is the number of scores read // so far and sum. Of. Scores is their sum System. out. print("Enter score (eof ends the data): "); score = sinp. read. Int( ); } 9 - 32
Afterwards l Once the loop has ended, we can compute the average score simply as follows: (double) sum. Of. Scores / number. Of. Scores l Why do we need to cast sum. Of. Scores to a double? What do we need to check before we do this computation? 9 - 33
What About Maximum and Minimum Scores? l Consider how the invariant could be changed to reflect the fact that, in addition to number. Of. Scores and sum. Of. Scores, we also have max. Of. Scores and min. Of. Scores: // The number. Of. Scores is the number // of scores read so far and sum. Of. Scores is // their sum; max. Of. Scores is the largest // score and min. Of. Scores is the smallest // score read so far 9 - 34
In Java Code l To maintain the truth of that invariant, we add the following to the loop: if (max. Of. Scores < score) //new largest score max. Of. Scores = score; if (min. Of. Scores > score) //new smallest score min. Of. Scores = score; l We must also initialize these two new variables, so the invariant is always true. We initialize them to the first score read. 9 - 35
public static void main (String[ ] args) { int score; int sum. Of. Scores = 0; int number. Of. Scores = 0; System. out. print("Enter score (eof ends the data): "); score = Simple. Input. in. read. Int( ); int max. Of. Scores = score; int min. Of. Scores = score; while ( !Simple. Input. in. eof( ) ) { number. Of. Scores++; //new score sum. Of. Scores += score; //update sum if (max. Of. Scores < score) //new largest score max. Of. Scores = score; if (min. Of. Scores > score) //new smallest score min. Of. Scores = score; // number. Of. Scores is the number of scores read // so far and sum. Of. Scores is their sum; max. Of. Scores is // the largest score and min. Of. Scores is the smallest // score read so far System. out. print("Enter score (eof ends the data): "); score = Simple. Input. in. read. Int( ); } … etc… 9 - 36
The break Statement in Loops l We saw the break statement before, in switch statements l They can also be used to terminate the execution of while and for loops l 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 9 - 37
Example while ( condition 1 ) { statement 1 if ( condition 2 ) break; statement 2 } With this use of the break statement, we can jump out of the loop in the middle. When is this useful? 9 - 38
The Loop-and-a-Half Problem l Before, we wrote the loop: read score while (!sinp. eof( )) { process score read score } l But what we really wanted was to execute read score process score as long as there are scores to process 9 - 39
But we had to read score to find out that there were no more scores l 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) 9 - 40
So we can use break l We might write it as follows: while (true) { read score if (sinp. eof( )) break; process score } That way, the “read” part of the “readprocess” loop doesn’t get written down twice, before the loop and during the loop 9 - 41
Invariants, Again l Java has added a new statement, the assert statement, that helps us write programs without bugs – “defensive programming” l Once you are confident of your program’s correctness, the asserts can be disabled in the final program (lowering overhead) l This material is taken from the Java programming site: http: //java. sun. com/j 2 se/1. 4. 2/docs/guide/lang/assert. html 9 - 42
Assertions l An assertion is a statement in Java that enables you to test your assumptions about your program l Each assertion contains a boolean expression that you believe will be true when the assertion executes l If it is not true, the system generates an error (an exception) l Assertions increase your confidence that your program is free of bugs! 9 - 43
Two Forms of assert You can write: assert exp 1; where exp 1 is a boolean expression you probably expect to be true l If it is false, Java generates an error l You can also write: assert exp 1 : exp 2; where exp 1 is a boolean expression you probably expect to be true, and exp 2 is any expression with a value (not void) l If exp 1 is false, Java generates an error and passes exp 2 as part of the error’s message (helps explain what happened) l 9 - 44
Three Situations to Use assert 1. Internal Invariants 2. Control-Flow Invariants 3. Preconditions, Postconditions, and Class Invariants We’ll look at examples of each… 9 - 45
1. Internal Invariants l Before there were assertions, programmers used comments to state their assumptions about a program’s behavior if (i % 3 == 0) {. . . } else if (i % 3 == 1) {. . . } else { // We know (i % 3 == 2) . . . } 9 - 46
1. Internal Invariants l You should now use an assertion whenever you would have written a comment that asserts an invariant if (i % 3 == 0) {. . . } else if (i % 3 == 1) {. . . } else { assert i % 3 == 2 : i; . . . } This assertion would actually fail when i is negative 9 - 47
2. Control-Flow Invariants l Place an assertion at a location you believe will not be reached l Write assert false; l However, note that if you put it (or any statement!) in a place that is technically unreachable according to the Java Language Specification, you will get a compile-time error…i. e. , put it somewhere technically reachable, but somewhere you don’t believe will be reached 9 - 48
2. Control-Flow Invariants l Old style void foo( ) { for (. . . ) { if (. . . ) return; } // Execution should never reach this point!!! } 9 - 49
2. Control-Flow Invariants l New style void foo( ) { for (. . . ) { if (. . . ) return; } assert false; // Execution should never reach this point!!! } 9 - 50
3. Preconditions, Postconditions, and Class Invariants l Preconditions — what must be true when a method is invoked l Postconditions — what must be true after a method completes successfully l Class invariants — what must be true about each instance of a class 9 - 51
3. Preconditions , Postconditions, and Class Invariants l Preconditions: do not use assertions to check the parameters of a public method (we don’t want these checks to be removed from a production program!) l Do use an assertion to test a nonpublic method’s precondition that you believe will be true no matter what a client does with the class (this means testing your own assumptions, not those of clients!) 9 - 52
3. Preconditions , Postconditions, and Class Invariants /** * When we turn off asserts, we lose this important check on the * value the client sent us. */ public void foo (int n) { assert n != 0; // BAD!!! Don’t use assert to check this! int b = 5/n; . . . } Do not use assertions to check the parameters of a public method! 9 - 53
3. Preconditions , Postconditions, and Class Invariants /** * Sets refresh interval (which must correspond to legal frame rate). * * @param interval refresh interval in milliseconds. */ private void set. Refresh. Interval(int interval) { assert interval > 0 && interval <= 1000/MAX_REFRESH_RATE : interval; . . . // Set the refresh interval } Example of using assert to check precondition in nonpublic method 9 - 54
3. Preconditions , Postconditions, and Class Invariants l Examples of using assert with postconditions and with class invariants can be found online http: //java. sun. com/j 2 se/1. 4. 2/docs/guide/lang/assert. html 9 - 55
Using Asserts l After regular compilation, assertions are in the. class files, but assertions can afterwards be “enabled” or “disabled” at runtime, meaning that you can “turn them on or off” at runtime (via the -enableassertions, or -ea, switch) l By default, assertions are completely disabled at runtime 9 - 56
(Simple) Example of Using Asserts public class Test. Assert { public static void main (String[] args) { assert false; } } 1. 2. If you run: java Test. Assert it runs fine (does nothing, of course). If you run: java -ea Test. Assert it will crash on the assertion (since it is “enabled”). 9 - 57