C# Program to insert an element in an array
In this program, You will learn how to insert an element in an array in C#.
List is : 30 40 50 60 70
Insert element: 45
Enter a location: 3
New List is: 30 40 45 50 60 70
Example: How to insert an element in an array in C#.
using System;
public class Program
{
public static void Main(string[] args)
{
int[] arr = new int[10];
int n, i, num, loc;
Console.Write("Enter size of an array:");
n = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter array elements:");
for (i = 0; i < n; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("Enter element for insert:");
num = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter location:");
loc = Convert.ToInt32(Console.ReadLine());
for (i = n; i >= loc; i--)
{
arr[i] = arr[i - 1];
}
n++;
arr[loc - 1] = num;
Console.Write("\nList After Insertion :");
for (i = 0; i < n; i++)
{
Console.Write(arr[i] + " ");
}
}
}
Output:
Enter size of an array:5
Enter array elements:10
20
30
40
50
Enter element for insert:99
Enter location:4
List After Insertion :10 20 30 99 40 50