C Program to Delete Duplicate Elements from an Array

In this tutorial, i am going to show you how to delete duplicate elements from an array with the help of standard method and function in c programs.

Programs to Delete Duplicate Elements from an Array in C

  • C Program to Delete Duplicate Elements from an Array using Standard Method
  • C Program to Delete Duplicate Elements from an Array using Function

C Program to Delete Duplicate Elements from an Array using Standard Method

#include <stdio.h>
 
int main()
{
    int a[10000],i,j,n,k=0,c=0 ;
   
    printf("Enter size of the array : ");
    scanf("%d", &n);
 
    printf("Enter elements in array : ");
    for(i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
    }
    
    for(i=0; i<n; i++)
    {
         if(a[i]!=-1)
		{
		    for(j=i+1; j<n; j++)
     
            {
        	   if(a[i]==a[j])
        	    {
			       c++;
			       a[j]=-1;
		       }
	       }
 		}
        if(a[i]!=-1)
        {
        	 a[k++]=a[i];
 
		} 
   
          
    }
       
    printf("elements after deleting duplicates in array :\n");
 
     
    for(i=0; i<n-c; i++)
    {
        
		printf("%d ",a[i]);
 
         
    }    
    return 0;
} 

The result of the above c program; as follows:

Enter size of the array : 8
Enter elements in array : 1 1 2 2 3 3 4 4
elements after deleting duplicates in array :
1 2 3 4 

C Program to Delete Duplicate Elements from an Array using Function

 #include <stdio.h>
 
int count(int *a,int n)
{ 
    int i,c=0,j,k=0;;
    for(i=0; i<n; i++)
    {
        if(a[i]!=-1)
		{
		    for(j=i+1; j<n; j++)
     
            {
        	   if(a[i]==a[j])
        	    {
			       c++;
			       a[j]=-1;
		       }
	       }
 		}
        if(a[i]!=-1)
        {
        	 a[k++]=a[i];
 
		} 
   
   
          
    }
    return n-c;
     
 }
 
 print(int *a,int n)
 { 
    int i;
    
 
    for(i=0; i<n; i++)
    {
         
        printf("%d  ",a[i]);
 
	}
 	
 }
int main()
{
    int a[10000],b[10000],i,n;
   
    printf("Enter size of the array : ");
    scanf("%d", &n);
 
    printf("Enter elements in array : ");
    for(i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
    }
    
    n=count(a,n);
    
	printf("elements after deleting duplicates in array :\n");
 
	print(a,n);   
    
	return 0;
}

The output of the above c program; as follows:

Enter size of the array : 5
Enter elements in array : 1 1 2 3 4
elements after deleting duplicates in array :
1  2  3  4  

Be First to Comment

Leave a Reply

Your email address will not be published.