Often we want to maintain a collection of values, for example, a grade in the range of 0 to 100 for each student in a class of size 30. We could declare 30 integer variables: int x1, x2, x3, .., x30; However, this gets messy and makes the resulting program too long. The answer is to use an array, which is a collection of variables all of the same class, having a single name and an easy way to access each variable, or element of the array.
Array Definition:
<class> <array name>[<# elements>];
OR
<class> <array name>[<# elements>] = {element1, element2, ..., last element};
Examples:
int StudentMarks[30];
int StudentAges[5] = {15, 16, 15, 17, 14};
In C++, the first element of the array is actually element 0, the next is element 1, and so on. This number is called the index of the element. This means that the last elemet in the array StudentMarks above is element29. The elements of the array are accessed using subscript notation, which involves putting the index of an element to be accessed in square brackets after the name of the array. We can read in and then write out the 30 values of the StudentMarks array in the following way (this would be much more trouble if we didn't have arrays):
int index;
for (index = 0; index < 30; index++) {
cout << "Enter mark for the student " << index + 1 << ":
";
}
for (index = 0; index < 30; index++) {
cout << "Mark " << index + 1 << ": ";
cout << StudentMarks[index] << endl;
}
Note the use of index + 1 in the for loops above. This is simply for "human consumption", because we typically begin counting things at 1, not 0.