Java Reference
In-Depth Information
Example 9-3 further illustrates how to process one-dimensional arrays.
EXAMPLE 9-3
This example shows how loops are used to process arrays. The following declaration is
used throughout this example:
double
[] sales =
new double
[10];
double
largestSale, sum, average;
The first statement creates the array
sales
of
10
elements, with each element of type
double
. The meaning of the other statements is clear. Also, notice that the value of
sales.length
is
10
.
Loops can be used to process arrays in several ways:
1. Initializing an array to a specific value: Suppose that you want to initialize
every element of the array
sales
to
10.00
. You can use the following loop:
for
(
int
index = 0; index < sales.length; index++)
sales[index] = 10.00;
2. Reading data into an array: The following loop inputs data into the
array
sales
. For simplicity, we assume that the data is entered at the
keyboard one number per line.
for
(
int
index = 0; index < sales.length; index++)
sales[index] = console.nextDouble();
3. Printing an array: The following loop outputs the elements of array
sales
. For simplicity, we assume that the output goes to the screen.
for
(
int
index = 0; index < sales.length; index++)
System.out.print(sales[index] + " ");
4. Finding the sum and average of an array: Because the array
sales
,
as its name implies, represents certain sales data, it may be desirable to
find the total sale and average sale amounts. The following Java code
finds the sum of the elements of the array
sales
(total sales) and the
average sale amount:
sum = 0;
for
(
int
index = 0; index < sales.length; index++)
sum = sum + sales[index];
if
(sales.length != 0)
average = sum / sales.length;
else
average = 0.0;
Search WWH ::
Custom Search