Finding the Unique elements in an array

Last Updated On Wednesday 19th Jan 2022

Find Unique Elements in Array in C

How to find the Unique Elements in an array, such that the repetitive elements in the array in C Program.

	Enter the length of the array: 4
Enter 5 elements in the array
1
2
3
2

The unique elements in the array are:
2
3
	

UniQue Elements in Array

Define two arrays, arr1 and arr2 , assign elements only to array arr1.arr2 left blank.

  • Start by copying the first element of the source array, arr1, into the target array, arr2, in other words, arr1[0] into array arr2[0].
  • The second array element of arr1, in other words, arr1[1], is compared with all the existing elements of array arr2.
  • Repeat until all the elements of array arr1 are compared with array arr2.
	#include<stdio.h>

#define max 100
int chkExists(int z[], int u, int v) {
  int i;
  for (i = 0; i < u; i++)
    if (z[i] == v) return (1);
  return (0);
}
void main() {
  int arr1[max], arr2[max];
  int m;
  int i, k;
  k = 0;
  printf("Enter length of the array:");
  scanf("%d", &m);
  printf("Enter %d elements of the arrayn", m);
  for (i = 0; i < m; i++)
    scanf("%d", &arr1[i]);
  arr2[0] = arr1[0];
  k = 1;
  for (i = 1; i < m; i++) {
    if (!chkExists(arr2, k, arr1[i])) {
      arr2[k] = arr1[i];
      k++;
    }
  }
  printf("nThe unique elements in the array are:n");
  for (i = 0; i < k; i++)
    printf("%dn", arr2[i]);
}
	
	Enter length of the array:5
Enter 5 elements of the array
11 11 2 2 33
The unique elements in the array are:
11
2
33