. For example, the
PART I
Chapter 7:
Arrays and Strings
139
PART I PART I
sample[3]: 3
sample[4]: 4
sample[5]: 5
sample[6]: 6
sample[7]: 7
sample[8]: 8
sample[9]: 9
Conceptually
, the
sample
array looks like this:
Arrays ar
e common in pr
ogramming because they let you deal easily with lar
ge numbers
of r
elated variables. For example, the following pr
ogram finds the average of the set of values
stor
ed in the
nums
array by cycling thr
ough the array using a
for
loop:
// Compute the average of a set of values.
using System;
class Average {
static void Main() {
int[] nums = new int[10];
int avg = 0;
nums[0] = 99;
nums[1] = 10;
nums[2] = 100;
nums[3] = 18;
nums[4] = 78;
nums[5] = 23;
nums[6] = 63;
nums[7] = 9;
nums[8] = 87;
nums[9] = 49;
for(int i=0; i < 10; i++)
avg = avg + nums[i];
avg = avg / 10;
Console.WriteLine("Average: " + avg);
}
}
The output fr
om the pr
ogram is shown her
e:
Average: 53
www.freepdf-books.com
140
P a r t I :
T h e C # L a n g u a g e
Initializing an Array
In the preceding program, the
nums
array was given values by hand, using ten separate
assignment statements. While that is perfectly correct, there is an easier way to accomplish
this. Arrays can be initialized when they are created. The general form for initializing a one-
dimensional array is shown here:
type
[ ]
array-name
= {
val1
,
val2
,
val3
, ...,
valN
};
Here, the initial values are specified by
val1
through
valN.
They are assigned in sequence,
left to right, in index order. C# automatically allocates an array large enough to hold the
initializers that you specify. There is no need to use the
new
operator explicitly. For example,
here is a better way to write the
Average
program:
// Compute the average of a set of values.
using System;
class Average {
static void Main() {
int[] nums = { 99, 10, 100, 18, 78, 23,
63, 9, 87, 49 };
int avg = 0;
for(int i=0; i < 10; i++)
avg = avg + nums[i];
avg = avg / 10;
Console.WriteLine("Average: " + avg);
}
}
As a point of interest, although not needed, you can use
new
when initializing an array.
For example, this is a proper, but redundant, way to initialize
nums
in the foregoing
program:
int[] nums = new int[] { 99, 10, 100, 18, 78, 23,
63, 9, 87, 49 };
Although redundant here, the
new
form of array initialization is useful when you are
assigning a new array to an already-existent array reference variable. For example:
int[] nums;
nums = new int[] { 99, 10, 100, 18, 78, 23,
63, 9, 87, 49 };
In this case,
nums
is declared in the first statement and initialized by the second.
One last point: It is permissible to specify the array size explicitly when initializing an
array, but the size must agree with the number of initializers. For example, here is another
way to initialize
nums
:
int[] nums = new int[10] { 99, 10, 100, 18, 78, 23,
63, 9, 87, 49 };
In this declaration, the size of
nums
is explicitly stated as 10.
www.freepdf-books.com