C++ Arrays
An array lets you store many values of the same type inside a single variable, instead of declaring a separate variable for each value. Arrays are one of the most important tools in C++ because they let you group related data together and work with it efficiently.
Creating an Array
To create an array, define the data type (like int or string), give the array a name, and specify how many elements it should hold inside square brackets. You can then fill the array with values using a comma-separated list wrapped in curly braces.
Declaring and initializing an array
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
return 0;
}
// Output: VolvoAccessing Array Elements
You reach a single element by writing its index number inside square brackets. A very important detail for beginners: array indexes start at 0, not 1. So the first element is at index 0, the second at index 1, and so on.
Changing an Element
To change the value of a specific element, refer to it by its index and assign a new value. The array keeps the same size; only the stored value changes.
Updating a value by index
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
return 0;
}
// Output: OpelOmitting the Size
- Declare a size to reserve empty slots you will fill later: int scores[5];
- Omit the size when you provide all values up front: int scores[] = {90, 85, 70};
- You can specify the size and provide fewer values; the remaining slots are set to 0 for numeric types.
Exercise: C++ Arrays
What index does the first element of a C++ array have?