An array in C++ stores multiple values of the same data type in a single variable. These values of the same data types in an array are its elements.
To create an array in C++, we define the variable type, the array’s name, and use a bracket []
specifying the number of elements it contains.
For example:
string names[3];
In the code above, we declare a string type of the variable 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"};
Here’s another example:
int mynumbers[5] = {1, 10, 5, 6, 95}
To change the value of a specific element of an array, we refer to its index number or position in the given array.
Remember that in C++, the first character or element of a given object has its index position or number as
0
. For example, the string “Theo” has its first characterT
as index0
while its second characterh
has its index number or position as1
, and so on.
#include <iostream> #include <string> using namespace std; int main() { // creating an array string names[3] = {"Theo", "Ben", "Dalu"}; // changing the first element of the array names[0] = "David"; // printing the new elwment cout << names[0]; return 0; }
names
, with 3
string elements.Theo
to David
by referring to its index number or position inside a square bracket [0]
.0
index of the array.RELATED TAGS
CONTRIBUTOR
View all Courses