C Program To Remove Duplicate Elements in an Array
In this tutorial, we are going to see how to write a C program to remove duplicate elements in an array. For example, if an array contains the following elements: 1, 1, 2, 2, 3, 4; So ‘1’ and ‘2’ occur twice. After deleting the duplicated element, we get the following array: 1, 2, 3, 4.
C Program To Remove Duplicate Elements in an Array
#include <stdio.h> int main() { int nbr, i, j, k; int arr[30]; printf("Enter the number of elements in the array: "); scanf("%d", &nbr); printf("Enter the array elements: "); for (i = 0; i < nbr; i++) scanf("%d", &arr[i]); // Remove duplicates for (i = 0; i < nbr; i++) { for (j = i + 1; j < nbr;) { if (arr[j] == arr[i]) { for (k = j; k < nbr; k++) { arr[k] = arr[k + 1]; } nbr--; } else j++; } } printf("Array without duplicates: "); for (i = 0; i < nbr; i++) { printf("%d ", arr[i]); } return 0; }
Output:
Enter the number of elements in the array: 6 Enter the array elements: 1 1 2 2 3 4 Array without duplicates: 1 2 3 4
[st_adsense]