Java Reference
In-Depth Information
}
ForLoop.java
This program produces the output
sum = 210
but you can try it out with different values for limit .
NOTE The more mathematically minded will realize that the sum of the integers
from 1 to n is given by the formula
. However, using that would not demon-
strate how a loop works.
How It Works
All the work is done in the for loop. The loop counter is i , and this is declared and initialized within
the for loop statement. The three elements that control the operation of the for loop appear between the
parentheses that follow the keyword for . In sequence, their purpose is to:
• Set the initial conditions for the loop, particularly the loop counter
• Specify the condition for the loop to continue
• Increment the loop counter
The control elements in a for loop are always separated by semicolons, but as you see later, any or all of
the control elements can be omitted; the two semicolons must always be present.
The first control element is executed when the loop is first entered. Here you declare and initialize the
loop counter i . Because it is declared within the loop, it does not exist outside it. If you try to output the
value of i after the loop with a statement such as
System.out.println("Final value of i = " + i); // Will not work
outside the loop
you find that the program no longer compiles.
Where the loop body consists of just a single statement, you can omit the braces and write the loop like
this:
for (int i = 1; i <= limit; ++i)
sum += i; // Add the current value of i
to sum
In general, it's better practice to keep the braces in as it makes it clearer where the loop body ends.
If you need to initialize and/or declare other variables for the loop, you can do it here by separating the
declarations by commas. For example, you could write the following:
for (int i = 1, j = 0; i <= limit; ++i) {
sum += i * j++; // Add the current value of
i*j to sum
Search WWH ::




Custom Search