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 character T as index 0 while its second character h has its index number or position as 1, and so on.

Code example

#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;
}

Code explanation

  • Line 7: We create a string type of the array, names, with 3 string elements.
  • Line 9: We change the first element of the array from Theo to David by 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 0 index of the array.

Free Resources