Find Common Elements between Two Arrays in C++
In this tutorial, we will learn how to find common elements between two arrays in C++.
Approach 1
The example program for finding out common elements between two arrays.
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
cout<<"Enter the array size of two arrays\n";
cin>>m>>n;
int arr1[m],arr2[n];
cout<<"Enter the array elements\n";
for(int i=0;i<m;i++)
{
cin>>arr1[i];
}
for(int i=0;i<n;i++)
{
cin>>arr2[i];
}
cout<<"\nThe commmon elements are : ";
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(arr1[i]==arr2[j])
cout<<arr1[i]<<" ";
}
}
return 0;
}Output :
Enter the array size of two arrays 3 5 Enter the array elements 1 2 3 2 3 4 5 6 The commmon elements are : 2 3
Explanation :
- At first, we need to take the size of the two arrays from the user.
- Then, we need to enter the array elements(of two arrays).
- Then the logic is structured by using two for loops.
- In the inner for loop, the condition is checked whether the elements of the two arrays are equal or not.in case that is equal then we just print that element.
Approach 2
Below is the example program for finding out common elements between the two arrays using the map.
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
cout<<"Enter the array size of two arrays\n";
cin>>m>>n;
int arr1[m],arr2[n];
map<int,int>mp;
cout<<"Enter the array elements\n";
for(int i=0;i<m;i++)
{
cin>>arr1[i];
mp[arr1[i]]++;
}
for(int i=0;i<n;i++)
{
cin>>arr2[i];
mp[arr2[i]]++;
}
cout<<"The Common elements are : ";
for(auto it :mp)
{
if(it.second>1)
cout<<it.first<<" ";
}
return 0;
}
Output :
Enter the array size of two arrays 2 3 Enter the array elements 1 5 5 2 3 The Common elements are : 5
Explanation :
- Even in this approach firstly, we have taken the sizes of two arrays from the user.
- Then, the user needs to enter the array of elements.
- Here we are finding the common elements by using a map (key as element and value as its frequency)
- Whenever we take the elements of the array from the user that element is added to the map so that its frequency gets updated.
- Then, whichever has the map value as greater than 1 was printed out as a common element.
Leave a Reply