Program to print all unique elements in an array

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 the size and elements of the array as input from the user.
  2. Initialize an array temp.
  3. Find the repetition of each element and store it in the temp array.
  4. After finding the repetition of each element, check if the repetition is 1. If so, print the element.

Code:

#include <iostream>
using namespace std;

int main()
{

    int array[100], temp[100];
    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;
}

Output

Enter size of array: 5

Enter elements in array: 2 3 1 2 1

Unique elements present in the array are: 3, 

Program to print all unique elements in an array