C# program to delete an item from a sorted array

Here, we are going to learn how to delete an item from a sorted array in C#.Net?
Submitted by Nidhi, on May 22, 2021 [Last updated : March 19, 2023]

Deleting Item from Sorted Array

Given a sorted array, we have to delete an item from it. Here, we will find the item from the sorted array and then perform shift operation by overwriting the data.

C# code for deleting item from sorted array

The source code to delete an item from a sorted array is given below. The given program is compiled and executed successfully.

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Declare to manage index of arrays
            int index = 0;

            //Location variable to store location from where we can remove item.
            int loc = -1;

            //Item to be deleted
            int item = 0;

            //Declare array that contains 5 integer elements
            int[] arr = new int[5];
            

            //Now read values for 5 array elements.
            Console.WriteLine("Enter value of array elements\n");
            for (index = 0; index < arr.Length; index++)
            {
                Console.Write("Element arr[" + (index + 1) + "]: ");
                arr[index] = int.Parse(Console.ReadLine());
            }

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

            //Now we find location to remove item
            for (index = 0; index < arr.Length; index++)
            {
                if (item==arr[index])
                {
                    loc = index;
                    break;
                }
            }

            if (loc != -1)
            {
                //Now we perform shift operations
                for (index = loc; index <= 3; index++)
                {
                    arr[index] = arr[index + 1];
                }

                //Copy item to location
                arr[4] = 0;

                Console.WriteLine("\nArray  Elements\n");
                for (index = 0; index < 4; index++)
                {
                    Console.Write(arr[index] + " ");
                }
            }
            else
            {
                Console.WriteLine("\nItem does not found in array");
            }
            
            Console.WriteLine();
        }
    }
}

Output

Enter value of array elements

Element arr[1]: 10
Element arr[2]: 20
Element arr[3]: 30
Element arr[4]: 40
Element arr[5]: 50
Enter item :
40

Array  Elements

10 20 30 50
Press any key to continue . . .

C# Basic Programs »

Comments and Discussions!

Load comments ↻





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