Examples:
Input:
arr1[ ] = {2, 7, 4, 8, 5}
arr2[ ] = {1, 2, 4, 5, 8}
Output for Union: 1 2 4 5 7 8
Output for Intersection: 2 4 5 8
Union
#include <bits/stdc++.h>
using namespace std;
// Function to find and print Union
void findUnion(int arr1[], int arr2[], int n1, int n2)
{
// Declare set
set<int> s;
// Inserting array elements in s
for (int i = 0; i < n1; i++)
s.insert(arr1[i]);
for (int i = 0; i < n2; i++)
s.insert(arr2[i]);
cout << "Union : ";
for (auto itr = s.begin(); itr != s.end(); itr++)
cout << *itr << " ";
}
// Main Function
int main()
{
int arr1[100], arr2[100], n1, n2;
cout << "Enter Number of elements for arr1: ";
cin >> n1;
for (int i = 0; i < n1; i++)
{
cin >> arr1[i];
}
cout << "Enter Number of elements for arr2: ";
cin >> n2;
for (int j = 0; j < n2; j++)
{
cin >> arr2[j];
}
findUnion(arr1, arr2, n1, n2);
return 0;
}
Output:
Enter Number of elements for arr1: 5
1 4 2 3 5
Enter Number of elements for arr2: 5
7 6 9 8 10
Union : 1 2 3 4 5 6 7 8 9 10
0 Comments