Chapter 5.1

10
IMPLEMENTING WHILE AND DO WHILE LOOP Chapter 5.1:

Transcript of Chapter 5.1

Page 1: Chapter 5.1

IMPLEMENTING WHILE AND DO

WHILE LOOP

Chapter 5.1:

Page 2: 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

Page 3: Chapter 5.1

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

Page 4: Chapter 5.1

The while statement

Page 5: Chapter 5.1

Example 1

Output ? 1 2 3 4

int i=1;

while (i<5){

System.out.print(i + “”);

i++;

}

Page 6: Chapter 5.1

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”);

Page 7: Chapter 5.1

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.

Page 8: Chapter 5.1

The do…while statement

Page 9: Chapter 5.1

Example 3

Output ? 0 1 2 3

int i=0;

do{

System.out.print(i + “”);

i++;

}while(i<=3);

Page 10: Chapter 5.1

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);