4.1 Arrays and Indexes
When you need many values of the same type, an array lets one name refer to a whole row of storage.
cpp
int scores[5] = {88, 92, 79, 95, 86};This creates five int cells. Their indexes start at 0, so the first value is scores[0] and the last value is scores[4].
cpp
std::cout << scores[0] << std::endl; // 88
scores[2] = 81;Arrays and loops are natural partners. A loop index can visit every element in order.
cpp
#include <iostream>
int main() {
int scores[5] = {88, 92, 79, 95, 86};
int total = 0;
for (int i = 0; i < 5; i++) {
total += scores[i];
}
double average = total / 5.0;
std::cout << "Average: " << average << std::endl;
return 0;
}The most common array mistake is an off-by-one error. For an array with length 5, scores[5] is outside the array. C++ does not automatically protect built-in array access, so the programmer must keep indexes in range.
Loading interactive lab...
Loading concept check...
Loading practice...