Q:

Delete given element from array using C# program

belongs to collection: C# Basic Programs | array programs

0

Given an array of integers and we have to delete a given element.

For example we have list of integer: 10 20 30 40 50

Here we want to delete 30 from array. We compare each element with given element; if we found element in array then we store position in a variable. And then perform shift operations to delete element from the list.

If we did not find given element into array then there is no need to perform shift operation. Because there is no need to delete any element from array.

 

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  = -1;
            int item = 0 ;

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

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

            for (i = 0; i < 5; i++)
            {
                if (item == arr1[i])
                {
                    pos = i;
                    break;
                }
            }

            if (pos == -1)
            {
                Console.WriteLine("Element did not find in array");
            }
            else
            {
                //Perform shift operations to delete item
                for (i = pos; i < arr1.Length - 1; i++)
                {
                    arr1[i] = arr1[i + 1];
                }

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

                }
            }
            Console.WriteLine();
        }
    }
}

Output

Enter numbers :
Element[1]: 10
Element[2]: 20
Element[3]: 30
Element[4]: 40
Element[5]: 50
Enter item to delete : 30
Array elements after deletion :
Element[1]: 10
Element[2]: 20
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
Find total number of occurrence of a given number ... >>
<< Delete an element from given position from array u...