In this tutorial, we’ll learn How to find all unique element in an Array in C#.
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | static void Main(string[] args) { int[] arr = new int[100]; ; int i, j, k, size, isUnique; //Reads size of the array Console.WriteLine("Enter size of the array: "); size = Convert.ToInt32(Console.ReadLine()); //Reads elements in array Console.WriteLine("Enter elements in the array: "); for (i = 0; i < size; i++) { arr[i] = Convert.ToInt32(Console.ReadLine()); } //Removing all duplicate elements from the array for (i = 0; i < size; i++) { // Assuming cuurent element is unique */ isUnique = 1; for (j = i + 1; j < size; j++) { //If any duplicate element is found if (arr[i] == arr[j]) { // Removing duplicate element for (k = j; k < size - 1; k++) { arr[k] = arr[k + 1]; } size--; j--; isUnique = 0; } } /* If array element is not unique then also remove the current element */ if (isUnique != 1) { for (j = i; j < size - 1; j++) { arr[j] = arr[j + 1]; } size--; i--; } } //Printing all unique elements in array Console.WriteLine("All unique elements in the array are: "); for (i = 0; i < size; i++) { Console.WriteLine(arr[i] + "\t"); } Console.ReadLine(); } |
Output: