View
233
Download
0
Embed Size (px)
Citation preview
Introduction to Computer Science
• Iteration–the while loop–the for loop
Unit 8Unit 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 ) + 32.0;
//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 C DEGREES F-10.0 14.0-9.0 15.8-8.0 17.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.”
8- 7
How Do WeDivide 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 ofLoop
Body ofLoop
Body ofLoop
After Loop
8- 8
Program is Organized as Follows
print first line of versewhile ( more verses ) {
print rest of verseprint 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 ) + 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
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. initialize2. 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;
}
initialize condition increment
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);}
8- 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
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. initialize2. 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 ) + 32.0; //Convert C to F System.out.println(“\t” + cent + “\t\t” + fahr);}
8- 17
do-while Loops
• Another form of loops in Java:
dostatement
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:
dostatement
while ( condition );
statementwhile ( 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): 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 ^Z
5 scores were entered.The average score was 75.6The maximum score was 93The minimum score was 51
8- 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
8- 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
8- 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
8- 25
Using the while Loop
read scorewhile ( not end of file ) {
process scoreread score
}
Short, clear, natural
8- 26
Using the do-while Loop
read scoreif ( not end of file )
do {process scoreread 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) {
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 … }}
8- 28
So Our While Loop Looks Like This
read scorewhile ( !sinp.eof( ) ) {
process scoreread score
}
8- 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
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)
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 scoresumOfScores = 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 largest scoremaxOfScores = score;
if (minOfScores > score) //new smallest scoreminOfScores = 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) {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 scoresumOfScores = sumOfScores +
score; //update sumif (maxOfScores < score) //new largest
scoremaxOfScores = 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…
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 ) {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?
8- 38
The Loop-and-a-Half Problem
• Before, we wrote the loop:read scorewhile (! sinp.eof( ) ) {
process scoreread score
}
• But what we really wanted was to executeread scoreprocess 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 scoreprocess 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 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