In this example, i’ll show you How to delete all duplicate elements from an Array in C# Console App.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
static void Main(string[] args) { int[] arr = new int[100]; int num; // Total number of elements in array int i, j, k; //Reads size of the array Console.WriteLine("Enter size of the array: "); num = Convert.ToInt32(Console.ReadLine()); //Reads elements in array Console.WriteLine("Enter elements in the array: "); for (i = 0; i < num; i++) { arr[i] = Convert.ToInt32(Console.ReadLine()); } // Finding all duplicate elements in array for (i = 0; i < num; i++) { for (j = i + 1; j < num; j++) { //If any duplicate found */ if (arr[i] == arr[j]) { // Delete the current duplicate element for (k = j; k < num; k++) { arr[k] = arr[k + 1]; } //Decrement size after removing duplicate element num--; // If shifting of elements occur then don't increment j j--; } } } // Print array after deleting duplicate elements Console.WriteLine("\nArray elements after deleting duplicates : "); for (i = 0; i < num; i++) { Console.WriteLine(arr[i]); } Console.ReadLine(); } |
Output: