RUN

# Program to find and print all unique elements of a given array of integers in C++

Written By -

## C++ program to find and print all unique elements of a given array of integers

Given: An array of integers, we have to find elements that are unique i.e., elements that are not repeated.

Example:

Given Array: [4, 12, 4, 2, 12, 20, 13]

Output: [2, 20, 13]

### # Algorithm

1. Take size and elements in the array as input from user.
2. Find the repetition of each element and store it in an array say temp.
3. Print array elements with repetition 1.

### Code:

``````#include<iostream>
using namespace std;

int main(){

int array, temp;
int n, i, j, cnt;
cout << "Enter size of array: ";
cin >> n;
cout << "\nEnter elements in array: ";

for (i = 0; i < n; i++){
cin >> array[i];
temp[i] = -1;
}

// Finding frequency of each element

for (i = 0; i < n; i++){
cnt = 1;
for (j = i + 1; j < n; j++){

if (array[i] == array[j]){
cnt++;
temp[j] = 0;
}
}

if (temp[i] != 0){
temp[i] = cnt;
}
}

// Printing all unique elements of the array
cout << "\nUnique elements present in the array are: ";
for (i = 0; i < n; i++){
if (temp[i] == 1){
cout << array[i] << ",  ";
}
}

return 0;

}``````

Related Posts:

Tutorials

Examples

Online Compilers

Interview Questions

Recent Articles