Chapter 5.1
Transcript of Chapter 5.1
IMPLEMENTING WHILE AND DO
WHILE LOOP
Chapter 5.1:
Repetition Statements
Repetition statement (or loop) a block of code to
be executed for a fixed number of times or until a
certain condition is met.
In JAVA, repetition can be done by using the
following repetition statements:
a) while
b) do…while
c) for
The while statement
The while statement evaluatesexpression/condition, which must return aboolean value. If the expression/condition istrue, the statement(s) in the while blockis/are executed.
Syntax:
while (expression/condition)
Statement(s);
It continues testing the expression/conditionand executing its block until theexpression/condition evaluates to false
The while statement
Example 1
Output ? 1 2 3 4
int i=1;
while (i<5){
System.out.print(i + “”);
i++;
}
Example 2
Output ? SUM : 1
SUM : 7
Good Bye
int sum=0, number =1;
while (number <= 10)
{
sum+=number;
number = number + 5;
System.out.println(“SUM :” + sum);
}
System.out.println(“Good Bye”);
The do…while statement
It is similar to while loops except it first executes the statement(s) inside the loop, and then evaluates the expression/condition. If the expression is true, the statement(s) in the do loop is/are executed again.
Syntax
do
statement(s);
while (expression);
It continues executing the statement until the expression/condition becomes false.
Note that the statement within the do loop is always executed at least once.
The do…while statement
Example 3
Output ? 0 1 2 3
int i=0;
do{
System.out.print(i + “”);
i++;
}while(i<=3);
Example 4
Output ? SUM : 2
SUM : 9
int sum=0, number =2;
do{
sum+=number;
number = number + 5;
System.out.println(“SUM :” + sum);
} while (number <= 10);