To remove duplicates from an array in C, you can use loops with a temporary array or a flag array to filter out duplicate elements.
In this example,
#include <stdio.h>
int main() {
int numbers[] = {1, 2, 2, 3, 4, 4, 5};
int n = sizeof(numbers) / sizeof(numbers[0]);
int temp[n];
int j = 0;
for (int i = 0; i < n; i++) {
int duplicate = 0;
for (int k = 0; k < j; k++) {
if (numbers[i] == temp[k]) {
duplicate = 1;
break;
}
}
if (!duplicate) {
temp[j++] = numbers[i];
}
}
printf("Array without duplicates: ");
for (int i = 0; i < j; i++) {
printf("%d ", temp[i]);
}
return 0;
}
Array without duplicates: 1 2 3 4 5
In this example,
#include <stdio.h>
int main() {
int numbers[] = {1, 2, 2, 3, 4, 4, 5};
int n = sizeof(numbers) / sizeof(numbers[0]);
int visited[n];
for (int i = 0; i < n; i++) {
visited[i] = 0;
}
printf("Array without duplicates: ");
for (int i = 0; i < n; i++) {
if (!visited[i]) {
printf("%d ", numbers[i]);
for (int j = i + 1; j < n; j++) {
if (numbers[i] == numbers[j]) {
visited[j] = 1;
}
}
}
}
return 0;
}
Array without duplicates: 1 2 3 4 5
In this tutorial, we learned How to Remove Duplicates in an Array in C language with well detailed examples.