C program to find only unique elements of array

//C++ Program to find only unique elements in array of integers.
using namespace std;
#include <stdio.h>
#include <string.h>
//#include <stdlib.h>
int main() {
   int arr[20], i, j, k, size;

   printf("\nEnter the size of the array : ");
   scanf("%d", &size);

   printf("\nEnter the Numbers in array : ");
   for (i = 0; i < size; i++)
      scanf("%d", &arr[i]);

   printf("\nArray with Unique elements is  : ");
   for (i = 0; i < size; i++) {
      for (j = i + 1; j < size;) {
         if (arr[j] == arr[i]) {
            for (k = j; k < size; k++) {
               arr[k] = arr[k + 1];
            }
            size--;
         } else
         {
            j++;
         }
      }
   }

   for (i = 0; i < size; i++) {
      printf("%d ", arr[i]);
   }
    printf("\n");
   return (0);
}
/*
Enter the size of the array : 8
Enter the Numbers in array :
1
2
2
3
4
2
3
1
Array with Unique elements is  : 1 2 3 4
*/
//C Program to remove all duplicate elements from an array
#include<iostream>
using namespace std;

class Base
{

};
void print(int* p)
{
while(*p)
cout<<*p++<<" ";
cout<<endl;
};
int main()
{
cout<<""<<endl;
int arr[]={1,2,2,3,3,2,4,5,5,55,555,5};

print(arr);
int size=sizeof(arr)/sizeof(arr[0]);
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;)
{
if(arr[i]==arr[j])
{
for(int k=j;k<size;k++)
{
arr[k]=arr[k+1];
}
//shift
size--;
}
else
{
//check next
j++;
}
}
}
print(arr);
return 0;
}
/*
1 2 2 3 3 2 4 5 5 55 555 5
1 2 3 4 5 55 555
*/

No comments:

Post a Comment