Home »
.Net »
C# Programs
Delete given element from array using C# program
Learn, how to delete given element from array of integers?
[Last updated : March 19, 2023]
Deleting given element from an array
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.
C# program to delete given element from an array
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
C# Basic Programs »