Let us say, we have a Array that contains three names, Mohan, John, Paul, Kriti and Salim.
And we want to replace the name John with a new name Neal.
#include <iostream> using namespace std; int main() { string arr[] = {"Mohan", "John", "Paul", "Kriti", "Salim"}; cout << "\nBefore replacing the second element\n"; for (string str : arr) { cout << str << endl; } arr[1] = "Neal"; cout << "\nAfter replacing the second element\n"; for (string str : arr) { cout << str << endl; } return 0; }
Before replacing the second element
After replacing the second element
So, in the above code we have created a Array and initialised to the variable x.
string arr[] = {"Mohan", "John", "Paul", "Kriti", "Salim"};
Now, let us see, how the values are positioned in the Array
Now, if we see the above diagram, John resides at position/index 1. So, what we do is, just replace the position/index 1 (i.e. arr[1]) with the new name Neal.
arr[1] = "Neal";
And the name John gets replaced with Neal.
And we get the below output,
Mohan Neal Paul Kriti Salim