while ( number <= 100 ) { sum = sum + number; number = number + 1; } The while Statement while ( ) { } Statement (loop body) Boolean Expression
Control Flow of while int sum = 0, number = 1 number <= 100 ? false sum = sum + number; number = number + 1; sum = sum + number; number = number + 1; true
Example Programs Puurginooo … out to reality … While10000.java Puurginooo … out to reality … WhileInput.java Puurginooo … out to reality … WhileBoolean.java
while Loop Pitfall - 1 Infinite Loops Both loops will not terminate because the boolean expressions will never become false. Infinite Loops Both loops will not terminate because the boolean expressions will never become false. int count = 1; while ( count != 10 ) { count = count + 2; } 2 2 int product = 0; while ( product < ) { product = product * 5; } 1 1
while Loop Pitfall - 2 Using Real Numbers Loop 2 terminates, but Loop 1 does not because only an approximation of a real number can be stored in a computer memory. Using Real Numbers Loop 2 terminates, but Loop 1 does not because only an approximation of a real number can be stored in a computer memory. float count = 0.0f; while ( count <= 1.0f ) { count = count f; } 2 2 float count = 0.0f; while ( count != 1.0f ) { count = count f; } 1 1
while Loop Pitfall - 3 Goal: Execute the loop body 10 times. count = 1; while (count < 10) {... count++; } 1 1 count = 0; while (count <= 10) {... count++; } 3 3 count = 1; while (count <= 10) {... count++; } 2 2 count = 0; while (count < 10) {... count++; } andexhibit off-by-one error. Grunk … out to reality … WhileLog.java
do { sum += number; number++; } while (sum <= ); The do-while Statement do { } while ( ); Statement (loop body) Boolean Expression
Control Flow of do-while int sum = 0, number = 1 sum += number; number++; sum += number; number++; sum <= ? true false
Example Programs Orque … out to reality … DoWhileInput.java Orque … out to reality … Do WhileDrink.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
for ( index = 0 ; index < 20 ; index++ ) { number = keyboard.nextInt(); sum += number; } The for Statement for ( ; ; ) Initialization Boolean Expression Update Statement (loop body) int index, sum = 0, number;
Control Flow of for i = 0; false number = inputBox.getInteger( ); sum += number; true i ++; i < 20 ?
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