Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
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:
string cars[4];
You can initialize it right away using curly braces:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
int myNum[3] = {10, 20, 30};
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.
cout << cars[0]; // Outputs "Volvo"
To change the value of a specific element, refer to the index number:
cars[0] = "Opel"; cout << cars[0]; // Now outputs "Opel"
Arrays are incredibly useful when you need to group related items together.
What is the index of the first element in a C++ array?