You will often want all individual values t
o be set to
zero. You can do that quickly by writing a
s follows:
int myArray[10] = {};
// Array of
// length 10 with all the value
s
// set to 0.
To access the individual values of an array
, you indicate
the value in square brackets for the index t
hat you want
to access. So if you think of the array as a t
able, the
index corresponds to the column number.
int myArray[100] = {};
// Array of
// length 100 with all values s
et to 0.
myArray[2] = 42;
// The value at index
// position 2 is now 42.
int x = myArray[2];
// x contains the
// value saved at index positio
n 2
// in myArray, in this case it i
s 42.
You may often want to calculate a new v
alue from all
the individual ones, for example the sum o
f all
individual values. Since you can now add
ress the
individual values via their index, you can e
asily do this
with a
for
loop:
// values is an array of length 1
00.
int sum = 0;
for (int index = 0; index < 100
;
++index) {
sum = sum + values[index];
}
With the first pass through the loop, the v
alue
values[0]
is added to
sum
. Then,
index
is raised by
1, and the next value is added. This is repe
ated until
the last value (
values[99]
) has been added.
In the next project, you will use an array t
o play a
musical scale.
!
NOTE!
Since the index for the first value is 0 rath
er than 1, the
highest possible index for an array of len
gth N is not N,
but rather N-1. With an array of length 10
0, in other
words, the highest possible index would b
e 99. If you use
a higher index, it will result in an error in t
he program
sequence. It’s impossible to predict what w
ould happen
then. So be careful only to use valid value
s for the index.
KNOWLEDGE BASE
42
CodeGamer manual inside english.indd 42
7/19/16 12:32 PM