Arrays are sequences of objects of the same type. We can declare an array of type char as follows:
int main()
{
char arr[5];
}
This example declares an array of 5 characters. To declare an array of type int
which holds five elements, we would use:
int main()
{
int arr[5];
}
To initialize an array, we can use the initialization list {}:
int main()
{
int arr[5] = { 10, 20, 30, 40, 50 };
}
Initialization list in our example { 10, 20, 30, 40, 50 } is marked with braces and elements separated by commas. This initialization list initializes our array with the values in the list. The first array element now has a value of 10; the second array element now has a value of 20 etc. The last (fifth) array element now has a value of 50.
We can access individual array elements through a subscript [] operator
and an index. The first array element has an index of 0, and we access it via:
int main()
{
int arr[5] = { 10, 20, 30, 40, 50 };
arr[0] = 100; // change the value of the first array element
}
Since the indexing starts from 0 and not 1, the last array element has an index of 4:
int main()
{
int arr[5] = { 10, 20, 30, 40, 50 };
arr[4] = 500; // change the value of the last array element
}
So, when declaring an array, we write how many elements we want to declare, but when accessing array elements, we need to remember that the indexing starts from 0 and ends with the number-of-elements – 1. That being said, in modern C++, we should prefer the std::array and std::vector containers to raw arrays. More on this in later chapters.