Arrays
An array stores a fixed-size, ordered collection of elements of the same type in contiguous memory, accessed by a numeric index starting at zero.
Declaring and Accessing Arrays
An array's size is fixed once declared. Elements are accessed with square brackets, and indexing always starts at 0 — the last valid index is the array's size minus one.
int scores[5] = {88, 92, 79, 100, 65};
for (int i = 0; i < 5; i++) {
std::cout << "Score " << i << ": " << scores[i] << std::endl;
}
scores[0] = 90; // update the first element
Two-Dimensional Arrays
A 2D array is useful for grid-like data such as a seating chart or a small matrix. It is accessed with two indices: row and column.
int grid[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 3; col++) {
std::cout << grid[row][col] << " ";
}
std::cout << std::endl;
}
Common Mistakes
- Accessing an index outside the array's bounds — C++ does not check this for you and it causes undefined behaviour.
- Forgetting that array indices start at 0, not 1.
- Trying to resize a plain array after it has been declared — its size is fixed at compile time.
- Assuming an array knows its own length — you must track the size separately or use
std::vectorfor dynamic sizing.
Professional Tip
For most real-world code, prefer std::vector (covered in the STL lesson) over raw arrays. It resizes dynamically and includes built-in bounds-aware methods, while plain arrays are best reserved for fixed, small, performance-critical collections.
Your Turn
Declare an array of 10 integers representing quiz scores. Write a loop that calculates and prints the average score.
Mini Quiz
What is the index of the first element in a C++ array?