Java Reference
In-Depth Information
LISTING 4.3
Continued
7:
8: for (int i = 0; i < denver.length; i++) {
9: total[i] = denver[i] + philadelphia[i];
10: System.out.format((i + 2003) + “ production: %,d%n”,
11: total[i]);
12: sum += total[i];
13: }
14:
15: System.out.format(“Average production: %,d%n”,
16: (sum / denver.length));
17: }
18: }
The output of the program is as follows:
2003 production: 5,000,000
2004 production: 5,800,000
2005 production: 7,300,000
Average production: 6,033,333
Instead of going through the elements of the three arrays one by one, this example uses a
for loop. The following things take place in the loop, which is contained in lines 8-13 of
Listing 4.3:
Line 8 —The loop is created with an int variable called i as the index. The index
increments by 1 for each pass through the loop and stops when i is equal to or
greater than denver.length , the total number of elements in the denver array.
n
Lines 9-11 —The value of one of the total elements is set using the loop index
and then displayed with some text identifying the year.
n
Line 12 —The value of a total element is added to the sum variable, which is used
to calculate the average yearly production.
n
Using a more general-purpose loop to iterate over an array enables you to use the pro-
gram with arrays of different sizes and still have it assign correct values to the elements
of the total array and display those values.
Java also includes a for loop that can be used to iterate through
all the elements of data structures such as vectors, linked lists,
hash sets, and other collections. It's covered along with those
structures on Day 8, “Data Structures.”
NOTE
 
Search WWH ::




Custom Search