Collections and Indexed Access
Programs rarely handle one value at a time; they process collections. An array (or list) stores an ordered sequence of values in a single named structure, accessed by index: a position number.
The defining feature is indexed access: element is retrieved directly by its position in constant time, without scanning from the start. Multi-dimensional arrays (arrays of arrays) represent matrices and grids, indexed by row and column.
| Operation | Description |
|---|---|
| Access / Update | Read or overwrite |
| Length | Total number of elements |
| Mutation | Append, insert, or remove elements |
| Traverse | Visit every element to compute or search |
Zero-Based Indexing
Most languages use zero-based indexing: the first element is at index 0, and the last of an -element array is at index (not ).
Accessing index is out of bounds: an error, and a frequent source of off-by-one bugs. For a list of length 5, valid indices are 0, 1, 2, 3, 4.
Arrays pair perfectly with loops: iterating an index from 0 to visits each element exactly once.
Common pitfall: Forgetting zero-based indexing and going out of bounds. Using instead of , or starting at1instead of0, triggers an out-of-bounds error.