C# Program to Delete an Item From a Sorted Array

Hi Hello, What I am going to do in this article I will see in detail about C# Program to Delete an Item From a Sorted Array. This article is a favorite of everyone and many people are suffering without knowing what the reason is. This article will be very useful for them.

C# Program to Delete an Item From a Sorted Array

C# Program to Delete an Item From a Sorted Array

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();
        }
    }
}
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 . . .

Final Words

By knowing clearly about C# Program to Delete an Item From a Sorted Array through this article. If you have any doubts please leave a comment via the comment box. Thank You.

Hi, I'm Selva a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment