Modifying Arrays
Part of the Fundamentals section of Coddy's C# journey — lesson 57 of 69.
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:
string[] my_array = {"apple", "banana", "cherry"};
my_array[1] = "orange";
System.Console.WriteLine(my_array[0] + ", " + my_array[1] + ", " + my_array[2]);Output:
apple, orange, cherrybanana was changed to an orange
Challenge
EasyCreate a method named ChangeElement that receives 3 arguments:
- First argument is an array
- Second argument is an index
- Third argument is a new element
The method will return a modified array by changing the element at the index stored in the second argument with the value in the third argument.
For example with the following arguments: ChangeElement(new string[] {"1", "2", "3"}, 0, "9") the method will return ["9", "2", "3"]
Input format (3 lines):
- Line 1: the array elements separated by commas (e.g.
a,b,c) - Line 2: the index of the element to replace (e.g.
1) - Line 3: the new element value (e.g.
d)
Output format: the modified array elements separated by spaces (e.g. a d c )
Cheat sheet
To modify an array element, assign a new value using its index:
string[] my_array = {"apple", "banana", "cherry"};
my_array[1] = "orange"; // Changes "banana" to "orange"Try it yourself
using System;
public class Program {
public static string[] ChangeElement(string[] arr, int index, string newElement) {
// Write code here
}
public static void Main(string[] args) {
string textArray = Console.ReadLine();
int index = int.Parse(Console.ReadLine());
string newElement = Console.ReadLine();
string[] arr = textArray.Split(',');
string[] modifiedArr = ChangeElement(arr, index, newElement);
for (int i = 0; i < modifiedArr.Length; i++) {
Console.Write(modifiedArr[i] + " ");
}
}
}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 Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 311Arrays Basics
Declaring ArraysAccessing ElementsModifying ArraysArray MethodsRecap - Product ArrayEdit Recap - Reversed Array