Modifying Elements
Part of the Fundamentals section of Coddy's C++ journey — lesson 60 of 74.
In addition to accessing the elements of an array, you can also modify them. To modify a specific element in an array, you can assign a new value to it using its index.
Here's an example:
std::string my_array[] = {"apple", "banana", "cherry"};
my_array[1] = "orange";
std::cout << my_array[0] << ", " << my_array[1] << ", " << my_array[2] << std::endl;Output:
apple, orange, cherrybanana was changed to an orange
Challenge
EasyCreate a program that:
- Receives three inputs in this order:
n: the number of elements in the arrayindex: an index position (0 to n-1)newElement: a new value (string)
- Then receives
nstrings to populate the array - Modifies the array by replacing the element at
indexwith the valuenewElement - Finally prints all elements of the modified array, one per line
For example for this input:
3
1
hello
apple
banana
cherryThe output is:
apple
hello
cherryExplanation: We have 3 elements. We replace index 1 (banana) with "hello".
Cheat sheet
To modify an array element, assign a new value using its index:
std::string my_array[] = {"apple", "banana", "cherry"};
my_array[1] = "orange"; // Changes "banana" to "orange"Try it yourself
#include <iostream>
#include <string>
int main() {
int n;
int index;
std::string newElement;
std::cin >> n;
std::cin >> index;
std::cin.ignore();
std::getline(std::cin, newElement);
std::string arr[n];
// Use n, index, arr and newElement to solve the problem
// You may also declare additional variables as needed
for (int i = 0; i < n; i++) {
// Populate arr
// Read a string value and store it in arr[i]
}
// Modify arr
// Set the element at position 'index' to 'newElement'
// print arr
// Loop through the array and print each element
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else