Array
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:
string cars[4];
We have now declared a variable that holds an array of four strings. To insert
values to it, we can use an array literal - place the values in a comma-
separated list, inside curly braces:
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.
cars[0] = "Opel";
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of Volvo
C++ Exercises
Test Yourself With Exercises
Exercise:
Create an array of type string called cars.
Example
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout << cars[i] << "\n";
}
This example outputs the index of each element together with its value:
Example
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout << i << " = " << cars[i] << "\n";
}
And this example shows how to loop through an array of integers:
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
Syntax
for (type variableName : arrayName) {
// code block to be executed
}
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}
Example
string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
...
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
cout << sizeof(myNumbers);
Result:
20
Why did the result show 20 instead of 5, when the array contains 5
elements?
You learned from the Data Types chapter that an int type is usually 4 bytes,
so from the example above, 4 x 5 (4 bytes x 5 elements) = 20 bytes.
To find out how many elements an array has, you have to divide the
size of the array by the size of the data type it contains:
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
int getArrayLength = sizeof(myNumbers) / sizeof(int);
cout << getArrayLength;
Result:
However, by using the sizeof() approach from the example above, we can
now make loops that work for arrays of any size, which is more sustainable.
Instead of writing:
It is better to write:
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < sizeof(myNumbers) / sizeof(int); i++) {
cout << myNumbers[i] << "\n";
}
Note that, in C++ version 11 (2011), you can also use the "for-each" loop:
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}