Labs ICT
โญ Pro Login

Arrays

An array is a collection of elements that all share the same data type, stored contiguously in memory. Think of it as a row of lockers โ€” each locker has a number (the index) and holds one item. Arrays have a fixed size that you set when you declare them.

Declaring and Initializing

You declare an array by specifying the element type, the name, and the size in square brackets. You can initialize it with a list of values right away:

#include <iostream>

int main() {
  int numbers[5] = {10, 20, 30, 40, 50};

  std::cout << "First element: " << numbers[0] << "\n";
  std::cout << "Third element: " << numbers[2] << "\n";

  numbers[1] = 25;

  std::cout << "Updated second element: " << numbers[1] << "\n";
  return 0;
}

Indexing starts at zero โ€” so numbers[0] is the first element and numbers[4] is the last. You can read values and assign new ones using the same bracket syntax.

Looping Through an Array

You almost always process arrays with loops. A for loop lets you step through every index:

#include <iostream>

int main() {
  int scores[6] = {88, 92, 75, 81, 96, 70};
  int total = 0;

  for (int i = 0; i < 6; i++) {
    total = total + scores[i];
  }

  std::cout << "Total score: " << total << "\n";
  std::cout << "Average: " << total / 6 << "\n";
  return 0;
}

The loop variable i goes from 0 to 5, giving you access to every element. It is a pattern you will see everywhere in C++ code.

Range-based For Loop (C++11)

Modern C++ gives you a cleaner way to iterate โ€” the range-based for loop. You do not need to manage the index yourself:

#include <iostream>

int main() {
  int values[5] = {2, 4, 6, 8, 10};

  for (int v : values) {
    std::cout << v << " ";
  }
  return 0;
}

This syntax works with any container that has a begin and end iterator. It is simpler and less error-prone than manual indexing.

๐Ÿงช Quick Quiz

How do you access the first element of an array called numbers?