Q:

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

belongs to collection: C# Basic Programs | array programs

0

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | array programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Reverse array elements using c# program... >>
<< Find palindrome numbers from array using C# progra...