C++ PROGRAMMING · 9 MIN STUDY

Arrays and indexed storage

An array stores a fixed number of same-typed elements and reaches each one by a zero-based index.

Learning objectives

  • Create and read a built-in array.
  • Explain why valid indexes start at zero and end at size minus one.

Prerequisites: variables, loops, and basic types. This lesson introduces built-in arrays; dynamic sequences are covered later with std::vector.

Contiguous elements

A built-in array keeps its elements in order. With four elements, the valid positions are 0, 1, 2, and 3. The expression scores[0] accesses the first element.

Complete C++17 program
#include <iostream>

int main() {
    int scores[4]{10, 20, 30, 40};
    int first = scores[0];
    int last = scores[3];

    std::cout << "First: " << first << '\n';
    std::cout << "Last: " << last << '\n';
}
Expected output First: 10 Last: 40

Trace and complexity

The index selects an offset from the first element, so normal indexed access is constant time, written O(1). An unsorted search must inspect elements until it finds a match or reaches the end, giving O(n) work in the worst case.

Common mistakes

  • scores[4] is outside this array. Built-in array subscripting does not add automatic bounds checking.
  • Do not use <= 4 when looping over four elements; the final valid index is 3.
  • For many everyday cases, prefer std::array or std::vector, which offer safer and richer interfaces.

Applications and summary

Arrays model fixed collections such as four quarterly values or a 3×3 grid. Their fast indexing makes them a central building block for algorithms.

Practice

  1. For int data[5], what is the last valid index?
  2. How many times does for (int i=0; i<5; ++i) execute?
  3. Why is data[5] not a valid element?
Show reasoned answers
  1. 4.
  2. Five times, for indexes 0 through 4.
  3. Array indexing starts at zero, so a five-element array has indexes 0 to 4.

References