Write a C program to remove duplicate elements in an array.
#include <stdlib.h>
int main () {
int *data, n, i, j, k, flag = 0, temp;
/* get the number of entries from the user */
printf("Enter the number of elements:");
scanf("%d", &n);
/* dynamically allocate memory to store entries */
data = (int *)malloc(sizeof (int) * n);
/* get the input entries from user */
for (i = 0; i < n; i++)
scanf("%d", &data[i]);
/* remove the duplicates */
for (i = 0; i < n - 1; i++) {
temp = data[i];
for (j = i + 1; j < n; j++) {
/* removing duplicate entries */
if (temp == data[j]) {
for (k = j; k < n - 1; k++)
data[k] = data[k + 1];
flag = 1;
n--;
j--;
}
}
}
/* print the results */
if (!flag)
printf("No duplicates in the given inputs\n");
else {
printf("After deleting duplicates:\n");
for (i = 0; i < n; i++)
printf("%d ", data[i]);
}
printf("\n");
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the number of elements:6
100 200 300 300 200 100
After deleting duplicates:
100 200 300
Enter the number of elements:6
100 200 300 300 200 100
After deleting duplicates:
100 200 300
No comments:
Post a Comment