Java Reference
In-Depth Information
The program produces the following output:
2 4 6 8 10
The For-Each Loop
Java has a loop construct that simplifies certain array loops. It is known as the
enhanced for loop, or the for-each loop. You can use it whenever you want to exam-
ine each value in an array. For example, the program Temperature2 had an array
variable called temps and the following loop:
for (int i = 0; i < temps.length; i++) {
if (temps[i] > average) {
above++;
}
}
We can rewrite this as a for-each loop:
for (int n : temps) {
if (n > average) {
above++;
}
}
This loop is normally read as, “For each int n in temps . . . .” The basic syntax of
the for-each loop is
for (<type> <name> : <array>) {
<statement>;
<statement>;
...
<statement>;
}
There is nothing special about the variable name, as long as you keep it consistent
within the body of the loop. For example, the previous loop could be written with the
variable x instead of the variable n :
for (int x : temps) {
if (x > average) {
above++;
}
}
 
Search WWH ::




Custom Search