C# Program to delete an element in an array


In this program, You will learn how to delete an element in an array in C#.


List is: 22 33 44 55 66

Enter for Delete: 44

A new list is: 22 33 55 66

Example: How to delete an element in an array in C#.

using System;
public class Program
{
    public static void Main(string[] args)
    {
        int i, n, num, p = 0;
        int[] arr = new int[10];

        Console.Write("Enter size of an array:");
        n = Convert.ToInt32(Console.ReadLine());
        Console.Write("Enter array elements:");
        for (i = 0; i < n; i++)
        {
            arr[i] = Convert.ToInt32(Console.ReadLine());
        }
        Console.Write("Enter element for delete:");
        num = Convert.ToInt32(Console.ReadLine());

		Console.Write("Before delete array elements:");
        for (i = 0; i < n; i++)
        {
			Console.Write(arr[i] + " ");
        }


        for (i = 0; i < n; i++)
        {
            if (arr[i] == num)
            {
                arr[i] = arr[i + 1];
                p = 1;
            }
            else if (p > 0)
            {
                arr[i] = arr[i + 1];
            }
        }

        Console.Write("\nList After Deletion :");
        for (i = 0; i < n - p; i++)
        {
            Console.Write(arr[i] + " ");
        }
    }
}

Output:

Enter size of an array:5
Enter array elements:10
20
30
40
50
Enter element for delete:40
Before delete array elements:10 20 30 40 50 
List After Deletion :10 20 30 50