EasyManua.ls Logo

Thames & Kosmos Code Gamer - Page 44

Thames & Kosmos Code Gamer
66 pages
Print Icon
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
You will often want all individual values to be set to
zero. You can do that quickly by writing as follows:
int myArray[10] = {}; // Array of
// length 10 with all the values
// set to 0.
To access the individual values of an array, you indicate
the value in square brackets for the index that you want
to access. So if you think of the array as a table, the
index corresponds to the column number.
int myArray[100] = {}; // Array of
// length 100 with all values set 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 position 2
// in myArray, in this case it is 42.
You may often want to calculate a new value from all
the individual ones, for example the sum of all
individual values. Since you can now address the
individual values via their index, you can easily do this
with a
for
loop:
// values is an array of length 100.
int sum = 0;
for (int index = 0; index < 100;
++index) {
s
um = sum + values[index];
}
With the first pass through the loop, the value
values[0]
is added to
sum
. Then,
index
is raised by
1, and the next value is added. This is repeated until
the last value (
values[99]
) has been added.
In the next project, you will use an array to play a
musical scale.
!
NOTE!
Since the index for the first value is 0 rather than 1, the
highest possible index for an array of length N is not N,
but rather N-1. With an array of length 100, in other
words, the highest possible index would be 99. If you use
a higher index, it will result in an error in the program
sequence. It’s impossible to predict what would happen
then. So be careful only to use valid values for the index.
KNOWLEDGE BASE

CodeGamer manual inside english.indd 42 7/19/16 12:32 PM