Iterative Statements: The While Statement Other Repetition Statements
Iterative Statements: The While Statement Other Repetition Statements
while ( condition ){
statement;
}
• If the condition is true, the statement is
executed
condition
evaluated
true false
statement
The while Statement
• An example of a while statement:
int count = 1;
while (count <= 5){
System.out.println (count);
count++;
}
int count = 1;
while (count <= 25){
System.out.println (count);
count = count - 1;
}
• This loop will continue executing until interrupted
(Control-C) or until an underflow error occurs
Nested Loops
• Similar to nested if statements, loops can be
nested as well
count1 = 1;
while (count1 <= 10){
count2 = 1;
while (count2 <= 20) {
System.out.println ("Here");
count2++;
}
count1++;
} 10 * 20 = 200
The do-while Statement
• A do-while statement (also called a do loop) has
the following syntax:
do{
statement;
}while ( condition )
statement
true
condition
evaluated
false
The do Statement
• An example of a do loop:
int count = 0;
do{
count++;
System.out.println (count);
} while (count < 5);
statement
condition
evaluated
true
condition
true false
evaluated
statement
false
The for Statement
• A for statement has the following syntax:
initialization
condition
evaluated
true false
statement
increment
The for Statement
• A for loop is functionally equivalent to the
following while loop structure:
initialization;
while ( condition ){
statement;
increment;
}
The for Statement
• An example of a for loop: