Techiehook Techiehook
Updated date Mar 18, 2024
Learn the basics of adding elements to an array in C# with this article. The provided C# program demonstrates a simple method to expand an array and add new elements.

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();
    }
}

 

  1. We start by declaring and initializing an array called numbers with five elements.
  2. The AddElementToArray method is created to add elements to the array. It takes the original array and the new element as parameters.
  3. Inside the AddElementToArray method, a new array (newArray) is created with a size increased by one compared to the original array.
  4. Array.Copy is used to copy the existing elements from the original array to the new array.
  5. The new element is added to the end of the new array.
  6. The modified array is returned and assigned to the original array in the Main method.
  7. 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 

ABOUT THE AUTHOR

Techiehook
Techiehook
Admin, Australia

Welcome to TechieHook.com! We are all about tech, lifestyle, and more. As the site admin, I share articles on programming, tech trends, daily life, and reviews... For more detailed information, please check out the user profile

https://www.techiehook.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!