RUN


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[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;

}

Report Error/ Suggestion

Related Posts:

[yuzo_views]



Interview Questions



CopyRight © 2020

CopyRight © 2020