C++ Arrays

C++ Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

Declaring an Array

To declare an array, define the variable type, specify the name of the array followed by square brackets [] and specify the number of elements it should store:

Example

string cars[4];

You can initialize it right away using curly braces:

Example

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
int myNum[3] = {10, 20, 30};

Accessing Elements

You access an array element by referring to the index number. Array indexes start with 0: [0] is the first element, [1] is the second element, etc.

Example

cout << cars[0]; // Outputs "Volvo"

Changing an Array Element

To change the value of a specific element, refer to the index number:

Example

cars[0] = "Opel";
cout << cars[0]; // Now outputs "Opel"

Arrays are incredibly useful when you need to group related items together.


Exercise

?

What is the index of the first element in a C++ array?