Arrays and Loops


Loops, and especially for loops, are ideal for processing arrays. No matter what you want to do to the array, you typically use a for loop with a loop counter that ranges from 0 through array-length-minus-1. Within the loop's body you perform whatever processing you want, using the loop counter as an array index.

For example, the following code computes the product of all the values in an array called measurements:

double product = 1; for (int i=0; i<measurements.length; i++)   product *= measurements[i];

Note that this code works on arrays of all sizes, because it reads the array size from measurements.length.

For another example, let's revisit the paycheck-printing code from the previous chapter. Here is one of the several versions of that code:

int id; for (id=1001; id<=1100; id++) {   float pay = getPayAmount(id);   printCheck(id, pay);   balance -= pay; }

The code is a bit unrealistic, because in a company with 100 employees, people are going to join or leave the company. The number of employees and their individual IDs are going to change. However, it is reasonable to assume that there could be a method called getIDsFromDatabase, which queries the corporate database and returns an array of int containing the ID of every employee who should get a paycheck. Then the preceding code would be modified as follows:

int[] ids = getIDsFromDatabase(); for (int id=0; id<ids.length; id++) {   float pay = getPayAmount(id);   printCheck(id, pay);   balance -= pay; }




Ground-Up Java
Ground-Up Java
ISBN: 0782141900
EAN: 2147483647
Year: 2005
Pages: 157
Authors: Philip Heller

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net