Transcript Slides

The while Statement
while ( <boolean expression> ) {
<statement>
}
Boolean Expression
while (
sum
Statement
(loop body)
number <= 100
=
sum + number;
number = number + 1;
}
) {
Control Flow of while
int sum = 0, number = 1
number <=
100 ?
false
true
sum = sum + number;
number = number + 1;
Example Programs
Puurginooo … out to reality … While10000.java
Puurginooo … out to reality … WhileInput.java
Puurginooo … out to reality … WhileBoolean.java
while Loop Pitfall - 1
1
int product = 0;
while ( product < 500000 ) {
product = product * 5;
}
Infinite Loops
2
int count = 1;
while ( count != 10 ) {
count = count + 2;
}
Both loops will not
terminate because the
boolean expressions will
never become false.
while Loop Pitfall - 2
1
float count = 0.0f;
while ( count != 1.0f ) {
count = count + 0.3333333f;
}
Using Real Numbers
2
float count = 0.0f;
while ( count <= 1.0f ) {
count = count + 0.3333333f;
}
Loop 2 terminates, but Loop
1 does not because only an
approximation of a real
number can be stored in a
computer memory.
while Loop Pitfall - 3
Goal: Execute the loop body 10 times.
1
count = 1;
2
while (count < 10) {
while (count <= 10) {
. . .
. . .
count++;
count++;
}
3
}
count = 0;
while (count <= 10) {
}
count = 1;
4
count = 0;
while (count < 10) {
. . .
. . .
count++;
count++;
}
1 and 3 exhibit off-by-one error.
Grunk … out to reality … WhileLog.java
The do-while Statement
do {
<statement>
} while (<boolean expression>);
do
{
sum += number;
number++;
} while (sum <= 1000000);
Boolean Expression
Statement
(loop body)
Control Flow of do-while
int sum = 0, number = 1
sum += number;
number++;
sum <= 1000000 ?
false
true
Example Programs
Orque … out to reality … DoWhileInput.java
Orque … out to reality … DoWhileDrink.java
Pre-test vs. Post-test loops
•
Use a pre-test loop for something that may be done
zero times
•
Use a post-test for something that is always done at
least once
The for Statement
for ( <initialization>; <boolean expression>; <update>
)
<statement>
int index, sum = 0, number;
Boolean
Expression
Initialization
for (
index = 0
;
index < 20
number = keyboard.nextInt();
sum += number;
}
Update
; index++
) {
Statement
(loop body)
Control Flow of for
i = 0;
false
i < 20 ?
true
number = inputBox.getInteger( );
sum
+= number;
i ++;
Example Programs
Poodyplat … out to reality … ForPrint.java
Poodyplat … out to reality … ForPower.java
Poodyplat … out to reality … ForFibonacci.java
The Nested-for Statement
Nesting a for loop inside another is a common
technique
ForTable.java
Challenge: Generate this table using nested-for loops.
Indefinite vs. Definite loops
•
For loops and while loops are exchangeable
but
•
Use a for loop when the number of iterations is
definite
•
Use a while or do-while when the number of
iterations depends on statements in the loop body