Delete duplicate elements from an array
C program to delete duplicate elements from an array.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void read_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:",i+1);
scanf("%d",&a[i]);
}
}
void print_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:%d\n",i+1,a[i]);
}
}
void delete(int a[MAX], int n)
{
int i, j, k;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
for(k=j;k<n;k++)
{
a[k] = a[k+1];
}
n = n-1;
//If shifting of elements occur then don't increment j
j--;
}
}
}
printf("\nModified array is\n");
print_array(a, n);
}
void main()
{
int arr[MAX];
int i, n;
printf("Enter the number of elements in the array\t:");
scanf("%d",&n);
printf("Enter the elements of the array\n");
read_array(arr, n);
delete(arr, n);
getch();
}
Output
Enter the number of elements in the array :8
Enter the elements of the array
Element 1 :12
Element 2 :23
Element 3 :45
Element 4 :12
Element 5 :45
Element 6 :23
Element 7 :65
Element 8 :23
Modified array is
Element 1 :12
Element 2 :23
Element 3 :45
Element 4 :65