Lesson 80 +10 XP

Arrays

Arrays

An array is a way to store many values of the same type under one name. Instead of five separate variables, you get one list with slots.

Declaring an array

int myNumbers[5] = {10, 20, 30, 40, 50};
  • The type (int) says what kind of values go inside.
  • myNumbers is the name of the array.
  • [5] says how many elements it has.
  • {10, 20, 30, 40, 50} is the list of starting values (the literal).

Accessing elements

Work with a single element by writing the array name followed by an index in square brackets:

cout << myNumbers[2];   // 30

Indexing starts at 0

Array indexes begin at 0, not 1. That means the first element lives at index 0, and the last element of a 5-element array sits at index 4:

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];   // Volvo  (the first element)
cout << cars[3];   // Mazda  (the last of the four)

Changing an element

You can overwrite any slot with a simple assignment:

cars[0] = "Opel";   // the first element is now "Opel"

TL;DR

  • An array stores many values of one type under a single name.
  • Declare with a type, name, size, and optional literal: int myNumbers[5] = {10, 20, 30, 40, 50};.
  • Reach an element with arrayName[index].
  • Indexes are 0-based, so the last slot of a 5-element array is index 4.
  • Overwrite a slot with cars[0] = "Opel";.