Menu
Coddy logo textTech

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, cherry

banana was changed to an orange

challenge icon

Challenge

Easy

Create a program that:

  1. Receives three inputs in this order:
    1. n: the number of elements in the array
    2. index: an index position (0 to n-1)
    3. newElement: a new value (string)
  2. Then receives n strings to populate the array
  3. Modifies the array by replacing the element at index with the value newElement
  4. Finally prints all elements of the modified array, one per line

For example for this input:

3
1
hello
apple
banana
cherry

The output is:

apple
hello
cherry

Explanation: 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;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals