Home » .Net

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

Here, we will learn insertion of an element in an array at given position. Here we will create array of integer that contains integer value, and insert an element at given (specified) position.

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.

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

Consider the example:

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






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.