C program to find the unique elements in an array.

CServer Side ProgrammingProgramming

Problem

Find the non-repeating element in an array by using the two loops. One is for the current element and the other is to check, if an element is already present in an array or not.

Solution

Consider an example given below −

15, 15, 16, 15, 13, 15

Here, the non-repeated elements in an array are 16 and 13.

Algorithm

Refer an algorithm given below for finding the unique or the non-repeated elements in an array.

Step 1 − Declare an array and input the array elements at run time.

Step 2 − Start traversing the array and check, if the current element is already present in an array or not.

Step 3 − If it is already present in an array then, move to the next element in an array and continue.

Step 4 − If not, output the element as the non-repeating element.

Example

Following is the C program for finding the unique or the non-repeated elements in an array −

 Live Demo

#include <stdio.h>
#include <stdlib.h>
int uniqueEle(int array[], int n){
   int i,j;
   int count = 1;
   for(i = 0; i < n; i++){
      for(j = 0; j < n; j++){
         if(array[i] == array[j] && i != j)
         break;
      }
      if(j == n ){
         printf("\nunique elements in an array is [%d] : %d \n",count,array[i]);
         ++count;
      }
   }
   return -1;
}
int main(){
   int n,i;
   printf("\nEnter no: of elements : ");
   scanf("%d",&n);
   int array[n];
   printf("\nenter the array elements : ");
   for(i = 0; i < n; i++){
      scanf("%d",&array[i]);
   }
   uniqueEle(array, n);
   return 0;
}

Output

When the above program is executed, it produces the following output −

Run 1:
Enter no: of elements: 5
enter the array elements :
11
11
15
16
13
unique elements in an array is [1] : 15
unique elements in an array is [2] : 16
unique elements in an array is [3] : 13
Run 2:
Enter no: of elements: 4
enter the array elements : 11
12
11
11
unique elements in an array is [1] : 12
raja
Published on 26-Mar-2021 07:07:05
Advertisements