Working with Arrays

Arrays are used to store multiple data items of the same type. In this lab, we will use an array to store a student's quiz scores. Once we have stored the quiz scores in the array, we can compute statistics such as the mean, median, minimum, or maximum score.

When declaring an array, the array name is followed by the array length in square brackets. Optionally, the array may be initialized when it is declared. For example,

int scores[5] = { 75, 92, 84, 68, 90 }; creates a five-long array of integers, and initializes the array with the values 75, 92, 84, 68, and 90.

To access an inividual element of an array, the array name is followed by the index of the element to be accessed in square brackets. Array indices always start at zero. For example, given the array declared above, we have that scores[0] has the value 75 and scores[2] has the value 84. The same syntax is used to modify an element of an array; for example,

scores[3] = 87; changes the value of scores[3] from 68 to 87.

Array Lengths

It is up to you, the programmer, to keep track of the length of any arrays you create: there is no sure way to determine the length of an array from the array itself. This is quite different from Python where you can use len() to determine the length of a list. Also, arrays in C and C++ can not be re-sized. If you create an array of length 10 and then want to store 11 items, you're out of luck! Unfortunately, the compiler may allow you to read and write beyond the declared length of an array, but this is a very bad thing (especially writing). If you are unsure how many data items will be stored in an array, you should declare it to be as long as the maximum number of items you expect to need. For example, if I am writing a program to compute statistics about students' scores on an exam, the length of the array should equal the number of students, even though a student or two may have missed the exam and thus not have a score:

const int NUM_STUDENTS = 100; int scores[NUM_STUDENTS] = { 0 }; What's going on with = { 0 }? This initializes the entire array to zero, and is a handy short-cut. Whenever an initialization list for an array has fewer values than the length of the array, the remainder of the array is filled with the zero value for the base type of the array. So, although it would be a strange thing to do, the following would initialize the array to 1, 2, 3 followed by 97 zeroes: const int NUM_STUDENTS = 100; int scores[NUM_STUDENTS] = { 1, 2, 3 };