Techiehook Techiehook
Updated date Jul 10, 2024
We will learn the basics of adding elements to an array in C# with this article.
  • 6.2k
  • 0
  • 0

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 

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!!!