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.
- First get the element to be inserted, say x
- Then get the position at which this element is to be inserted, say pos
- Create a new array with the size one greater than the previous size
- Copy all the elements from previous array into the new array till the position pos
- Insert the element x at position pos
- Insert the rest of the elements from the previous array into the new array after the pos
using System;
public class GFG {
static public void Main()
{
int n = 10;
int [] arr = new int [n];
int i;
for (i = 0; i < n; i++)
arr[i] = i + 1;
for (i = 0; i < n; i++)
Console.Write(arr[i] + " " );
Console.WriteLine();
int x = 50;
int pos = 5;
int [] newarr = new int [n + 1];
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];
}
for (i = 0; i < n + 1; i++)
Console.Write(newarr[i] + " " );
Console.WriteLine();
}
}
|
Output:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 50 5 6 7 8 9 10
Last Updated :
28 Aug, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...