Java Reference
In-Depth Information
You should get the result:
sum = 210
How It Works
The while loop is controlled wholly by the logical expression that appears between the parentheses
that follow the keyword while . The loop continues as long as this expression has the value true , and
how it ever manages to arrive at the value false to end the loop is up to you. You need to be sure that
the statements within the loop will eventually result in this expression being false . Otherwise you
have an infinite loop.
How the loop ends in our example is clear. We have a simple count as before, and we increment i in
the loop statement that accumulates the sum of the integers. Sooner or later i will exceed the value of
limit and the while loop will end.
You don't always need to use the testing of a count limit as the loop condition. You can use any logical
condition you want.
And last, but not least, we have the do while loop.
Try It Out - The do while Loop
As we 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. We 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);
}
}
How It Works
The statements within the loop are always executed at least once because the condition determining
whether the loop should continue is tested at the end of each iteration. Within the loop we 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 will contain 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. We could rewrite the
loop so that only one statement was within the loop, in which case the braces are not required. For instance:
Search WWH ::




Custom Search