C# | How to insert an element in an Array?

An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C#.

Let’s say we have an array and we want to insert an element at a specific position in this array.

Here’s how to do it.



  1. First get the element to be inserted, say x
  2. Then get the position at which this element is to be inserted, say pos
  3. Create a new array with the size one greater than the previous size
  4. Copy all the elements from previous array into the new array till the position pos
  5. Insert the element x at position pos
  6. Insert the rest of the elements from the previous array into the new array after the pos
filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to insert an 
// element in an array
using System;
  
public class GFG {
  
    // Main Method
    static public void Main()
    {
  
        int n = 10;
        int[] arr = new int[n];
        int i;
  
        // initial array of size 10
        for (i = 0; i < n; i++)
            arr[i] = i + 1;
  
        // print the original array
        for (i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
        Console.WriteLine();
  
        // element to be inserted
        int x = 50;
  
        // position at which element 
        // is to be inserted
        int pos = 5;
  
        // create a new array of size n+1
        int[] newarr = new int[n + 1];
  
        // insert the elements from the 
        // old array into the new array
        // insert all elements till pos
        // then insert x at pos
        // then insert rest of the elements
        for (i = 0; i < n + 1; i++) {
            if (i < pos - 1)
                newarr[i] = arr[i];
            else if (i == pos - 1)
                newarr[i] = x;
            else
                newarr[i] = arr[i - 1];
        }
  
        // print the updated array
        for (i = 0; i < n + 1; i++)
            Console.Write(newarr[i] + " ");
        Console.WriteLine();
    }
}

chevron_right


Output:

1 2 3 4 5 6 7 8 9 10 
1 2 3 4 50 5 6 7 8 9 10


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.