Home » » how to remove duplicate elements in Array with one loop

how to remove duplicate elements in Array with one loop

This program will tell u how to remove duplicates elements from  an array. In this program two concepts only used. First check out duplicates elements and then shift one elements towards left of that element.




First of all main call redundantElement() method that will call sort for sorting the array in first line. Now sorted array we compare current element with next element. If we able to find out then we will shift all array elements left means a[j-1]=a[j] upto ith position. display() function is used to display the values of array.





//Program to delete duplicates items from an array






#include<conio.h>
#include<stdio.h>


void sort(int *a,int n)
{
     for(int i=0;i<n;i++)
    {
        for(int j=0;j<n-i;j++)
       {
          if(a[j]>a[j+1])
         {
            int temp=a[j];
            a[j]=a[j+1];
            a[j+1]=temp;
         }
      }
   }
}



int redundantElement(int *a,int n)
{

sort(a,n);
   

for(int i=1;i<n;)
{

  if(a[i-1]==a[i])
  {
      for(int j=i;j<n;j++)
       {

           a[j-1]=a[j];
       }
       n--;
       continue; 
  }
  else
  i++;
 }

 return n;
 

}


void display(int a[],int n)
{  
      printf("\n");
     for(int i=0;i<n;i++)
     printf("%d  ",a[i]);
}



int main()
{
    int a[10],n;
   printf("Enter No of Element\n");
   scanf("%d",&n);


for(int i=0;i<n;i++)
{
     scanf("%d",&a[i]);
}
n=redundantElement(a,n);
display(a,n);
return 0;
}



Output://



 

Share this article :

0 comments:

Post a Comment

 
My Other Websites : Ad Networks | Games Copyright © 2014. Study Depth - All Rights Reserved