Java Reference
In-Depth Information
The two versions of the for loop have quite different mechanisms controlling the number of iterations.
You can also see quite clearly that the primary difference between the while loop and the do-while loop is
where the test is carried out.
Let's explore each of these loops in turn and see how they work in a practical context.
TRY IT OUT: The Numerical for Loop
Let's start with a very simple example. Suppose you want to calculate the sum of the integers from 1 to
a given value. You can do this using the for loop as shown in the following example:
public class ForLoop {
public static void main(String[] args) {
int limit = 20;
// Sum from 1 to this value
int sum = 0;
// Accumulate sum in this
variable
// Loop from 1 to the value of limit, adding 1 each cycle
for(int i = 1; i <= limit; ++i) {
sum += i;
// Add the current value of i
to sum
}
System.out.println("sum = " + sum);
}
Search WWH ::




Custom Search