Q:

Delete an element from given position from array using C# program

belongs to collection: C# Basic Programs | array programs

0

Given array of integers and we have to delete (remove) an element from given position.

To delete element from array: first we will traverse array to given position and then we will shift each element one position back.

The final array will not contain that element and array size will be decreased by 1.

For example we have list of integers:

10 12 15 8 17 23

Now we delete element from 3rd position then list will like this:
10 12 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[] 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 to delete item : ");
            pos = int.Parse(Console.ReadLine());

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

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

            Console.WriteLine();
        }
    }
}

Output

Enter numbers :
Element[1]: 10
Element[2]: 20
Element[3]: 30
Element[4]: 40
Element[5]: 50
Enter position to delete item : 2
Array elements after deletion :
Element[1]: 10
Element[2]: 30
Element[3]: 40
Element[4]: 50

 

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
Delete given element from array using C# program... >>
<< Reverse array elements using c# program...