Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to find the unique elements in an array.
In C programming, finding unique elements in an array means identifying elements that appear exactly once. This is a common array manipulation problem that can be solved using nested loops to compare each element with all other elements.
Syntax
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(array[i] == array[j] && i != j)
break;
}
if(j == n) {
// Element is unique
}
}
Algorithm
Follow these steps to find unique elements in an array −
- Step 1 − Declare an array and input elements at runtime.
- Step 2 − Use outer loop to traverse each element.
- Step 3 − Use inner loop to check if current element appears elsewhere.
- Step 4 − If no duplicate found, the element is unique.
Example
The following program finds all unique elements in an array using nested loops −
#include <stdio.h>
void findUniqueElements(int array[], int n) {
int i, j;
int count = 1;
printf("\nUnique elements in the array:<br>");
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
if(array[i] == array[j] && i != j)
break;
}
if(j == n) {
printf("Element [%d] : %d<br>", count, array[i]);
count++;
}
}
}
int main() {
int array[] = {15, 15, 16, 15, 13, 15};
int n = sizeof(array) / sizeof(array[0]);
printf("Array elements: ");
for(int i = 0; i < n; i++) {
printf("%d ", array[i]);
}
findUniqueElements(array, n);
return 0;
}
Array elements: 15 15 16 15 13 15 Unique elements in the array: Element [1] : 16 Element [2] : 13
How It Works
The algorithm uses two nested loops −
- The outer loop picks each element one by one
- The inner loop checks if the picked element appears anywhere else in the array
- If the inner loop completes without finding a duplicate (j == n), the element is unique
- Time complexity is O(n²) and space complexity is O(1)
Key Points
- This method preserves the order of unique elements as they appear in the original array
- The condition
i != jensures we don't compare an element with itself - Each unique element is printed only once, even if the algorithm encounters it multiple times
Conclusion
Finding unique elements using nested loops is a straightforward approach with O(n²) time complexity. While not the most efficient for large arrays, it's simple to understand and implement for basic array problems.
Advertisements
