How to change an array element in C++
Overview
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.
Creating an array
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}
Changing the element of an array
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 characterTas index0while its second characterhhas its index number or position as1, and so on.
Code example
#include <iostream>#include <string>using namespace std;int main() {// creating an arraystring names[3] = {"Theo", "Ben", "Dalu"};// changing the first element of the arraynames[0] = "David";// printing the new elwmentcout << names[0];return 0;}
Code explanation
- Line 7: We create a string type of the array,
names, with3string elements. - Line 9: We change the first element of the array from
TheotoDavidby referring to its index number or position inside a square bracket[0]. - Line 13: We print the new element, which can still be found in the
0index of the array.