Loading lessons...
Arrays and Loops
Arrays and Loops
The real power of an array shows up when you process every element. The classic partner is a for loop.
The classic pattern
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < 4; i++) {
cout << cars[i] << "\n";
}
istarts at 0 and keeps going whilei < 4.- The loop visits indexes 0, 1, 2, and 3 - exactly the valid ones.
Why i < 4 and not i <= 4?
The array has 4 elements, so its legal indexes are 0 through 3. The condition i < 4 stops right at 4. If you wrote i <= 4, the loop would be trying to read cars[4], which doesn't exist.
Range-based loop (the easy way)
When you don't need the index, a range-based loop is simpler and safer:
for (string car : cars) {
cout << car << "\n";
}
It hands you each element in order, with no counting bookkeeping at all.
TL;DR
- Loop over an array with a
forloop. - Use
i < arraySizeso the loop stays inside the valid indexes. cars[i]pulls the element at indexi.- A range-based loop
for (element : array)visits every element without an index. - Keep the loop within the array bounds.