C++ program to find union and intersection of two unsorted arrays

C++Server Side ProgrammingProgramming

In this article, we will be discussing a program to find the union and intersection of two given unsorted arrays.

Let us denote the two arrays with ‘A’ and ‘B’. Then union of those arrays is denoted by A ∪ B which is basically an array of all the elements in both the given arrays; provided that each element repeats only once.

To find this, we will create a separate array and copy down all the elements from the first array. Then we will traverse through the elements of the second array and check if it is already present in the union array. If it isn’t, then we will add it to the union array.

Similarly, intersection of two arrays will be denoted by A ∩ B. It is an array of the elements that are present in both the given arrays.

For this, we will traverse through the elements of the first array one by one. Simultaneously we will be checking if that element is present in the second array or not. If the element is present in both the arrays, then we will add it to an intersection array.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int len1 = 4, len2 = 3, flag1 = 0, flag2 = 0;
   int array1[len1] = {1,2,3,4}, array2[len2] = {5,3,4};
   int uni[len1+len2] = {1,2,3,4}, inter[len1];
   for(int k = 0; k < len2 ; k++) {
      flag1 = len1;
      for(int m = 0; m < len1; m++) {
         //eliminating common elements among the given arrays
         if(array2[k] == uni[m])
            break;
         else if(m == len1-1) {
            uni[flag1] = array2[k];
            flag1 = flag1+1;
         }
      }
   }
   for(int q = 0; q < len1; q++) {
      for(int w = 0; w < len2; w++) {
         //checking if both arrays contain a particular element
         if(array1[q] == array2[w]) {
            inter[flag2] = array1[q];
            flag2 = flag2+1;
            break;
         }
      }
   }
   cout << "Union :" <<endl;
   for(int u = 0; u < flag1; u++) {
      cout << uni[u] << " ";
   }
   cout << "\nIntersection :" <<endl;
   for(int i = 0; i < flag2; i++) {
      cout << inter[i] << " ";
   }
   return 0;
}

Output

Union :
1 2 3 4
Intersection :
3 4
raja
Published on 03-Oct-2019 11:13:36
Advertisements