An array in C++ is used to store multiple elements of the same data type. These values of the same data types in an array are its elements.
To declare an array in C++, we write the data type, the name of the array with a bracket []
specifying the number of elements it contains.
For example:
string names[3];
In the code above, we declared an array that holds three string elements. We can now use an array literal with a comma-separated list inside curly braces to insert the elements into the array.
For example:
string names[3] = {"Theo", "Ben", "Dalu"};
Another example:
int mynumbers[5] = {1, 10, 5, 6, 95}
We can easily access the elements of a given array by referring to their index number. Remember that in C++, the first element of a given object has its index position or number as 0
.
For example, the string Theo
has its first character T
as index 0
while its second character h
has its index number or position as 1
and so on.
In the code below, we will create an array with three elements and refer to each array element using their index numbers.
#include <iostream>#include <string>using namespace std;int main() {// creating an arraystring names[3] = {"Theo", "Ben", "Dalu"};// accessing the first element of the arraycout << names[0]<<endl;// accessing the second element of the arraycout << names[1];return 0;}
names
having 3
string elements.[0]
.[1]
.