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,
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,
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: