Repetition
Java Lab
Repetition control structure
while
do….while
for
while repetition statement
the program tests the loop-continuation
condition at the beginning of the loop,
before executing the loop's body
Example 1
Flo
w cha
r
START
t
COUNTER ß 1
Start
counter 1
COUNTER <= 10
DOWHILE counter <= 10
Display “HELLO ”
TRUE
counter counter + 1
DISPLAY
“HELLO” ENDDO
FALSE Display “Done !”
COUNTER ß COUNTER+1 Stop
e
cod
d o
DISPLAY
seu
“DONE”
P
STOP
Example 1 (cont’d) - while
public class Hello {
public static void main (String[] args)
{
int counter;
Initialize counter
counter=1;
Test
while(counter<=10){
System.out.println("Hello");
counter=counter+1; Increment
}
System.out.println("Done");
}
}
do…while repetition
statement
do...while statement tests the loop-
continuation condition after executing the
loop's body
Example - do…while
public class HelloDoWhile {
public static void main (String[] args) {
int counter;
Initialize counter
counter=1;
do{
Increment System.out.println("Hello");
counter=counter+1;
}while(counter<=10);
Test
System.out.println("Done");
}
}
for repetition statement
The while statement can be used to
implement any counter-controlled loop.
Java also provides the for repetition
statement, which specifies the counter-
controlled-repetition details in a single line
of code.
Example - for
Test
public class HelloFor {
public static void main (String[] args) {
int counter; Increment
Initialize counter
for(counter=1; counter<=10; counter++){
System.out.println("Hello");
}
System.out.println("Done");
}
}
Simple test
Try print star ********
Exercise 1
Get and display the names, ages and
heights of 5 students.
Exercise 2
Get the height of 30 students.
Display “You are very tall”
if the student’s height
is greater than 1.7meters.
Otherwise,
display “Ordinary height”
Exercise 3
Find the average age of 10 workers.
Display the average age.