C program to find the unique elements in an array.


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("
unique elements in an array is [%d] : %d
"
,count,array[i]);          ++count;       }    }    return -1; } int main(){    int n,i;    printf("
Enter no: of elements : "
);    scanf("%d",&n);    int array[n];    printf("
enter 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

Updated on: 14-Sep-2023

25K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements