Arrays
beginnerWhat you'll learn
- Explain why an array replaces many separate variables.
- Declare an array and access elements with 0-based indices.
- Traverse an array without reading out of bounds.
An array is a collection of elements of the same type stored in contiguous memory.
Problem
You must store the marks of 50 students. Declaring 50 separate variables does not scale:
Goal: Store many marks under one name so a single loop can process them.
An array stores many values of the same type under one name, so a single loop can handle them all:
That is why arrays exist. The rest of this note shows how to declare, index, and traverse them.
Arrays and loops are the two biggest stuck points in an intro course. Spend extra time on 0-based indexing and have students trace a loop by hand before moving on.
Declaring Arrays
Accessing Elements
Array Size
Modifying Elements
Common Mistakes
- Array index out of bounds (no runtime check!)
- Using variable index in C-style array: arr[i] is OK, but arr[n] where n is not constant is fine in C++
- Forgetting arrays are 0-indexed
- Comparing arrays: arr1 == arr2 doesn't work (compares addresses)
Debug
This loop is meant to print all 5 elements but reads one past the end: for (int i = 0; i <= 5; i++) cout << arr[i] << ' ';. Find and fix the bug.
Key takeaway: Arrays store same-type elements in contiguous memory — always check bounds and remember indices start at 0.
Try it: Declare an array of 5 scores, fill them with user input, and print the average.