Arrays and indexed storage
An array stores a fixed number of same-typed elements and reaches each one by a zero-based index.
Learning objectives
- Create and read a built-in array.
- Explain why valid indexes start at zero and end at size minus one.
Prerequisites: variables, loops, and basic types. This lesson introduces built-in arrays; dynamic sequences are covered later with std::vector.
Contiguous elements
A built-in array keeps its elements in order. With four elements, the valid positions are 0, 1, 2, and 3. The expression scores[0] accesses the first element.
#include <iostream>
int main() {
int scores[4]{10, 20, 30, 40};
int first = scores[0];
int last = scores[3];
std::cout << "First: " << first << '\n';
std::cout << "Last: " << last << '\n';
}Trace and complexity
The index selects an offset from the first element, so normal indexed access is constant time, written O(1). An unsorted search must inspect elements until it finds a match or reaches the end, giving O(n) work in the worst case.
Common mistakes
scores[4]is outside this array. Built-in array subscripting does not add automatic bounds checking.- Do not use
<= 4when looping over four elements; the final valid index is 3. - For many everyday cases, prefer
std::arrayorstd::vector, which offer safer and richer interfaces.
Applications and summary
Arrays model fixed collections such as four quarterly values or a 3×3 grid. Their fast indexing makes them a central building block for algorithms.
Practice
- For
int data[5], what is the last valid index? - How many times does
for (int i=0; i<5; ++i)execute? - Why is
data[5]not a valid element?
Show reasoned answers
- 4.
- Five times, for indexes 0 through 4.
- Array indexing starts at zero, so a five-element array has indexes 0 to 4.