Adding Elements to an Array in C#
Arrays are a fundamental data structure in programming, allowing us to store and manipulate collections of elements. In C#, we can add elements to an array using various methods.
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();
}
}
Output:
Original Array:
1 2 3 4 5
Array After Adding Elements:
1 2 3 4 5 6 7
Comments (0)