
Think together · Start with a story
A girl needs to record the scores of five classmates. Giving every score a separate name is easy to muddle, so she draws a row of numbered storage slots.
Break down the process
- One name for the groupscores
- Index 0Stores 90
- Index 1Stores 85
- Index 2Stores 72
An array stores values of the same type in order. Use one name and an index to select an element.
The picture shows only three slots. An array for five people has five positions, with indexes from 0 to 4. The position number and index differ by 1, so check the index carefully before reading a score.
01A few variables are fine—but what about many values?
Suppose you want to store five students' scores. You could write:
int score1, score2, score3, score4, score5;
But this becomes difficult to manage if there are 100 or 1,000 values.
An array is a tool for working with “a group of values of the same kind.”
02What is an array?
An array is a group of elements of the same type, arranged in order.
int scores[5] = {90, 85, 72, 100, 68};
03How is an array different from many separate variables?
Many separate variables
Each has a different name, so it is difficult to process them all with one loop.
An array
One name represents the group; use an index to select an element.
04How do you access one element in an array?
std::cout << scores[0];
std::cout << scores[3];
scores[0] is the first element, and scores[3] is the fourth.
05Do array elements have to use the same type?
For an ordinary C++ array, yes.
int numbers[3];
double prices[3];
char letters[3];
Elements in one array have the same type, so each element uses the same size and interpretation.
06Does an array change its length by itself?
The length of an ordinary C++ array is fixed after it is created.
int a[5];
This array always has five int elements. It cannot automatically “become an array of 10” halfway through the program.
What you have learned
- An array stores a group of values of the same type in order.
- One array name can manage many elements.
- You can access an element using an index.
- The length of an ordinary C++ array is fixed.
- Arrays work well with loops for processing groups of data.
Next: What Does an Array Look Like in Memory?
Your turn to try
Is the fifth student's score at scores[5]?
Ready? Open to see the explanation
It is at scores[4]. Counting five positions from 0 gives 0, 1, 2, 3, 4. Index 5 is already out of bounds.