Java Reference
In-Depth Information
5. If none of the divisors divide into number without a remainder, it is a prime, so enter the existing
number in the first available empty slot in the array and then move to the next iteration for a new
candidate number .
6. When the array of primes is full, stop looking for new primes and output all the prime number val-
ues from the array.
Arrays of Arrays
You have worked only with one-dimensional arrays up to now, that is, arrays that use a single index. Why
would you ever need the complications of using more indexes to access the elements of an array?
Consider a specific example. Suppose that you have a fanatical interest in the weather, and you are intent
on recording the temperature each day at 10 separate geographical locations throughout the year. After you
have sorted out the logistics of actually collecting this information, you can use an array of 10 elements cor-
responding to the number of locations, where each of these elements is an array of 365 elements to store the
temperature values. You declare this array with the statement:
float[][] temperature = new float[10][365];
This is called a two-dimensional array because it has two dimensions — one with index values running
from 0 to 9, and the other with index values from 0 to 364. The first index relates to a geographical location,
and the second index corresponds to the day of the year. That's much handier than a one-dimensional array
with 3650 elements, isn't it?
Figure 4-4 shows the organization of the two-dimensional array.
FIGURE 4-4
There are 10 one-dimensional arrays that make up the two-dimensional array, and they each have 365
elements. In referring to an element, the first pair of square brackets encloses the index for a particular array
and the second pair of square brackets encloses the index value for an element within that array. So to refer
to the temperature for day 100 for the sixth location, you use temperature[5][99] . Because each float
variable occupies 4 bytes, the total space required to store the elements in this two-dimensional array is 10
× 365 × 4 bytes, which is a total of 14,600 bytes.
 
 
Search WWH ::




Custom Search