Write a C program to remove duplicate elements in an array.
#include <stdio.h>
#define MAX 256
#define DUP 1
int main() {
int i, j, n, data[MAX][2];
/* get the number of inputs from the user */
printf("Number of elements in input array:");
scanf("%d", &n);
/* get the array entries from the user */
printf("Enter your array entries:\n");
for (i = 0; i < n; i++) {
printf("Data[%d]: ", i);
scanf("%d", &data[i][0]);
data[i][1] = 0;
}
/* mark the duplicates in the array */
for (i = 0; i < n; i++) {
if (data[i][1])
continue;
for (j = i + 1; j < n; j++) {
if (data[i][0] == data[j][0]) {
data[j][1] = DUP;
}
}
}
j = 0;
#define MAX 256
#define DUP 1
int main() {
int i, j, n, data[MAX][2];
/* get the number of inputs from the user */
printf("Number of elements in input array:");
scanf("%d", &n);
/* get the array entries from the user */
printf("Enter your array entries:\n");
for (i = 0; i < n; i++) {
printf("Data[%d]: ", i);
scanf("%d", &data[i][0]);
data[i][1] = 0;
}
/* mark the duplicates in the array */
for (i = 0; i < n; i++) {
if (data[i][1])
continue;
for (j = i + 1; j < n; j++) {
if (data[i][0] == data[j][0]) {
data[j][1] = DUP;
}
}
}
j = 0;
/* remove the duplicates from the source array */
for (i = 0; i < n; i++) {
if (!data[i][1]) {
data[j++][0] = data[i][0];
}
}
/* print the resultant array */
printf("\nData in the resultant array:\n");
for (i = 0; i < j; i++) {
printf("%d ", data[i][0]);
}
printf("\n");
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Number of elements in input array:5
Enter your array entries:
Data[0]: 10
Data[1]: 20
Data[2]: 10
Data[3]: 20
Data[4]: 30
Data in the resultant array:
10 20 30
Number of elements in input array:5
Enter your array entries:
Data[0]: 10
Data[1]: 20
Data[2]: 10
Data[3]: 20
Data[4]: 30
Data in the resultant array:
10 20 30
No comments:
Post a Comment