Java Reference
In-Depth Information
TRY IT OUT: The do-while Loop
And last, but not least, you have the do-while loop.
As I said at the beginning of this topic, the do-while loop is much the same as the while loop, except
for the fact that the continuation condition is checked at the end of the loop. You can write an integer-
summing program with this kind of loop too:
public class DoWhileLoop {
public static void main(String[] args) {
int limit = 20; // Sum from 1 to this value
int sum = 0; // Accumulate sum in this
variable
int i = 1; // Loop counter
// Loop from 1 to the value of limit, adding 1 each cycle
do {
sum += i;
// Add the current value of i
to sum
i++;
} while(i <= limit);
System.out.println("sum = " + sum);
}
}
DoWhileLoop.java
The output is the same as the previous example.
How It Works
The statements within the do-while loop are always executed at least once because the condition that
determines whether the loop should continue is tested at the end of each iteration. Within the loop you
add the value of i to sum , and then increment it. When i exceeds the value of limit , the loop ends, at
which point sum contains the sum of all the integers from 1 to limit .
The loop statement here has braces around the block of code that is within the loop. You could rewrite
the loop so that only one statement was within the loop body, in which case the braces are not required.
For example:
do
sum += i; // Add the current value of
i to sum
while(++i <= limit);
Of course, you can and should still put the braces in. I advise that you always use braces around the body
of a loop, even when it is only a single statement.
Search WWH ::




Custom Search