Real-Life Example
Lesson outline
Why arrays are useful in real programs
Arrays are useful when you need to keep a fixed number of related values of the same type together. Instead of creating separate variables for each value, you can store the values in one collection and process them with a loop.
Common examples include quiz scores for a class, daily temperatures for a week, inventory counts for known shelves, or sensor readings captured at fixed intervals.
Example: class quiz scores
Suppose an instructor records five quiz scores and wants to calculate the class average and find the highest score. An array keeps the scores grouped under one meaningful name.
What the array gives us
- One variable name represents the whole group of scores.
- Indexes let us access each score, such as scores[0], scores[1], and scores[2].
- A loop lets us apply the same operation to every element.
- The array size is fixed here, so the loop must stay inside the valid index range.
Avoid magic numbers
The example above works, but writing the number 5 in multiple places can create maintenance problems. If the array size changes later, every related value must be updated correctly.
A safer beginner-friendly pattern is to store the size in a named constant and use that constant in the declaration and loop.
When a vector may be better
A built-in array is fine when the number of elements is known and fixed. If the number of values can grow or shrink, prefer std::vector because it tracks its size and is easier to manage safely.
In production C++, std::array is also a strong choice for fixed-size collections because it behaves more like a standard library container while still keeping a fixed size.
Practice direction
Try changing the scores, adding a lowest-score calculation, or counting how many students scored at least 90. These are realistic operations where arrays and loops work together.