Adding Elements to an Array in C#
Arrays are a fundamental data structure in programming, allowing you to store and manipulate collections of elements. In C#, you can add elements to an array using various methods.
C# Program to Add Elements to an Array in C#:
using System;
class Program
{
static void Main()
{
// Declare and initialize an array
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
Console.WriteLine("Original Array:");
DisplayArray(numbers);
// Add elements to the array
numbers = AddElementToArray(numbers, 6);
numbers = AddElementToArray(numbers, 7);
Console.WriteLine("\nArray After Adding Elements:");
DisplayArray(numbers);
}
static int[] AddElementToArray(int[] array, int element)
{
// Create a new array with increased size
int[] newArray = new int[array.Length + 1];
// Copy existing elements to the new array
Array.Copy(array, newArray, array.Length);
// Add the new element to the end of the new array
newArray[newArray.Length - 1] = element;
return newArray;
}
static void DisplayArray(int[] array)
{
foreach (var element in array)
{
Console.Write(element + " ");
}
Console.WriteLine();
}
}
- We start by declaring and initializing an array called
numbers
with five elements. - The
AddElementToArray
method is created to add elements to the array. It takes the original array and the new element as parameters. - Inside the
AddElementToArray
method, a new array (newArray
) is created with a size increased by one compared to the original array. Array.Copy
is used to copy the existing elements from the original array to the new array.- The new element is added to the end of the new array.
- The modified array is returned and assigned to the original array in the
Main
method. - The
DisplayArray
method is created to print the elements of an array.
Output:
Original Array:
1 2 3 4 5
Array After Adding Elements:
1 2 3 4 5 6 7
Comments (0)