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 

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.