The variables we have worked with so far can hold only one value at a time. For example, if you declare an integer variable named testScore to represent a student s test score, that variable can hold only one test score.
The fact that the variable testScore can hold only one test score is not a problem so long as that student only takes one test. However, if the same student takes another test, or another student takes the same test, where do you store the second test score? If you store the second score in testScore, then you lose the ability to retrieve the first score from the variable testScore, since that variable can hold only one test score at a time.
Therefore, if you wanted to keep track of, for example, 100 test scores, your code might look like this:
int testScore1; int testScore2; int testScore3; int testScore4; int testScore5; int testScore6; int testScore7; int testScore8; int testScore9; int testScore10; // declare testScore11 through testScore99 int testScore100;
Yikes! That s a lot of code to write. Wouldn t it be easier just to declare 1 variable that can hold 100 values, like this:
The good news is you can do exactly that, using an array! An array enables you to use a single variable to store many values. The values are stored at consecutive indexes, starting with zero and then incrementing by one for each additional element of the array.
Using 1 array variable to store 100 values has many advantages over having to declare 100 separate variables that can hold only 1 value each. In addition to being a lot less code to write, it is far easier to keep track of 1 variable than 100. Furthermore, and more important, as I will show you in this chapter, you can use a loop to access each consecutive element in an array, whereas this is not possible with three separate variables.