Insert an element at given position into array using C# program

Given an array, we have to insert an element at a given position into it.
[Last updated : March 19, 2023]

Inserting an element at given position into an array

Given an array of integers and we have to insert an item (element/number) at specified (given) position.

To insert element into an array at given position:

We have to reach at that particular position by traversing the array, shift all elements one position ahead. And then insert the element at given position.

Example

For example we have list of integers:

10 12 15 8 17 23

Now we insert new element 17 at 3rd position then
10 12 17 15 8 17 23

C# program to insert an element at given position into an array

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1 {
  class Program {
    static void Main() {
      int i = 0;
      int pos = 0;
      int item = 0;
      int[] arr = new int[10];

      //Read numbers into array
      Console.WriteLine("Enter numbers : ");
      for (i = 0; i < 5; i++) {
        Console.Write("Element[" + (i + 1) + "]: ");
        arr[i] = int.Parse(Console.ReadLine());
      }

      Console.Write("Enter position : ");
      pos = int.Parse(Console.ReadLine());

      Console.Write("Enter new item : ");
      item = int.Parse(Console.ReadLine());

      //Perform shift opearation
      for (i = 5; i >= pos; i--) {
        arr[i] = arr[i - 1];
      }

      arr[pos - 1] = item;

      //print array after insertion
      Console.WriteLine("Array elements after insertion : ");
      for (i = 0; i < 6; i++) {
        Console.WriteLine("Element[" + (i + 1) + "]: " + arr[i]);
      }

      Console.WriteLine();
    }
  }
}

Output

Enter numbers :
Element[1]: 20
Element[2]: 13
Element[3]: 15
Element[4]: 16
Element[5]: 27

Enter position : 3
Enter new item : 17

Array elements after insertion :
Element[1]: 20
Element[2]: 13
Element[3]: 17
Element[4]: 15
Element[5]: 16
Element[6]: 27

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.