Next: Observations on the do
Up: Unit 06
Previous: Example of for loop:
In a while loop, the condition of end of loop is checked at the
beginning of each iteration. A do loop is similar to a while
loop, with the only difference that the condition of end of loop is
checked at the end of each iteration.
do statement
Syntax:
do
statement
while (condition);
- condition is an expression of type boolean
- statement is a single statement (also called the
body of the loop)
Semantics: is equivalent to
statement;
while (condition)
statement
Hence:
- First, the statement is executed.
- Then, the condition is evaluated, and if it is true,
the statement is executed again, continuing in this way
until the condition becomes false.
- At this point the statement immediately following the do loop
is executed.
Example: Print out 100 stars.
int i = 0;
do {
System.out.print("*");
i++;
} while (i < 100);
Next: Observations on the do
Up: Unit 06
Previous: Example of for loop: