Repetition Control Structures
Objectives
• Appreciate the usefulness of control structures
• Apply control statements in accomplishing programming tasks
What are Repetition Control Structures?
• Java statements that allows us to execute specific blocks of code a
number of times
• Three types of repetition control structures:
• While loop
• do-while loop
• for loop
• make sure that you add some statements that will allow your loop to
terminate at some point
The while loop
• statement or block of statements that is repeated as long as some
condition is satisfied.
while( boolean_expression ){
statement1;
statement2;
...
}
The while loop
Example
int myIntVariable = 10;
while(myIntVariable > 0) {
System.out.println(myIntVariable);
myIntVariable = myIntVariable - 1;
}
The do-while Loop
• Similar to the while loop
• Main difference between a while and do-while loop is that, the statements
inside a do-while loop are executed at least once
do{
statement1;
statement2;
...
}while( boolean_expression );
• statements inside the do-while loop are first executed, and then the
condition in the boolean_expression part is evaluated
The do-while Loop
Example:
int x = 0;
do
{
System.out.println(x);
x++;
}while (x<10);
The for loop
Structure:
for (InitializationExpression; LoopCondition; StepExpression){
statement1;
statement2;
...
}
The for loop
• InitializationExpression -initializes the loop variable.
• LoopCondition - compares the loop variable to some limit value.
• StepExpression - updates the loop variable
Example:
int i;
for( i = 0; i < 10; i++ ){
System.out.print(i);
}
Exercises:
1. Grades
• Get three exam grades from the user and compute the average of the
grades. Output the average of the three exams. Together with the
average, also include a smiley face in the output if the average is
greater than or equal to 60, otherwise output :-(.
Exercises
2. Ten Times
• Create a program that prints your name a ten times.
• Do three versions of this program using a while loop, a do-while loop and a
for-loop.
Exercises
3. Powers
• Compute the power of a number given the base and exponent.
• Do three versions of this program using a while loop, a do-while loop and a
for-loop.