Delete Duplicate Elements in Array in C++
Advertisements
Delete Duplicate Elements from Array Program in C++
Array is collection of similar data type, In this code we enter only Integer type values and remove all duplicate value form array list. To delete all duplicate elements from array list you need looping and if else statement.
In below program we compared each element with all other elements. If the element is equal to any other element in the array then shift all the elements to left by one place. The process is repeated till all the elements are compared.
Example
Given Array with Duplicate Elements: 4 5 8 9 5 12 7 New Array with Unique Elements: 4 5 8 9 12 7
C++ Program to Remove Duplicate Elements in an Array
#include<iostream.h> #include<conio.h> void main() { int arr[20], i, j, k, size; clrscr(); cout<<"\nEnter Size of an Array: "; cin>>size; cout<<"\nEnter any" <<size <<" Numbers : "; for (i = 0; i < size; i++) cin>>arr[i]; cout<<"\nArray with Unique list : "; for (i = 0; i < size; i++) { for (j = i + 1; j < size;) { if (arr[j] == arr[i]) { for (k = j; k < size; k++) { arr[k] = arr[k + 1]; } size--; } else j++; } } for (i = 0; i < size; i++) { cout<<arr[i]; } getch(); }
Output
Enter Size of an Array : 5 Enter any 5 Numbers : 3 4 7 6 4 Array with Unique list : 3 4 7 6
Google Advertisment