Prime

#### Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

#### Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

# C++ Program to Display the distinct elements of an array

## C++ Program to display distinct elements of the array

Here, in this section we will discuss the C++ program to display distinct elements of the array. One of the way to do so is by using hash = map, we can declare a map which keeps the track of the frequency of the elements, So we can print those key of the map whose frequency is 1.

Given an integer array, we have to print all the distinct element of the input array.

#### Example

input: a[ ]={10,20,10,9,6,2,6}

Output: 20 2 9

## Algorithm :

• Take the size of the array from the user and store it in variable n.
• Declare an array of size n and take n input elements of the array from the user.
• Declare a map that store the frequency of the elements of the array.
• Now, iterate the entire map and print the elements whose frequency is 1.

## C++ Program to display distinct elements of the array based on above algorithm

`#include<bits/stdc++.h>using namespace std;int main(){    int n;    cin>>n;    int a[n];    map<int, int>mp;    for(int i=0; i<n; i++){        cin>>a[i];        mp[a[i]]++;    }    cout<<"Distinct elements : ";    for(auto it = mp.begin(); it != mp.end(); it++){        if(it->second == 1)        cout<<a[i]<<" ";    }    return 0;}`
`Output :51 2 3 1 4Distinct elements : 2 3 4`