Here are C++ programs to find the union and intersection of two arrays. First program finds union of two arrays and second program finds intersection of two arrays.
C++ program to find the union of two arrays
#include<iostream>
using namespace std;
int main()
{
int a1[20],a2[20],k=0,num,unio[40],flag=0;
cout<<"How many elements to be stored (max 20) : ";
cin>>num;
cout<<"Enter elements of array a1 : ";
for(int i=0;i<num;i++,k++)
{
cin>>a1[i];
unio[k]=a1[i];
}
cout<<"Enter elements of array a2 : ";
for(int i=0;i<num;i++,k++)
{
cin>>a2[i];
unio[k]=a2[i];
}
cout<<"a1 union a2 : ";
for(int i=0;i<k;i++)
{
for(int y=i+1;y<k;y++)
if(unio[i]==unio[y])
flag=1;
if(flag==0)
cout<<unio[i]<<" ";
flag=0;
}
return 0;
}
using namespace std;
int main()
{
int a1[20],a2[20],k=0,num,unio[40],flag=0;
cout<<"How many elements to be stored (max 20) : ";
cin>>num;
cout<<"Enter elements of array a1 : ";
for(int i=0;i<num;i++,k++)
{
cin>>a1[i];
unio[k]=a1[i];
}
cout<<"Enter elements of array a2 : ";
for(int i=0;i<num;i++,k++)
{
cin>>a2[i];
unio[k]=a2[i];
}
cout<<"a1 union a2 : ";
for(int i=0;i<k;i++)
{
for(int y=i+1;y<k;y++)
if(unio[i]==unio[y])
flag=1;
if(flag==0)
cout<<unio[i]<<" ";
flag=0;
}
return 0;
}
OUTPUT
C++ program to find the intersection of two arrays
#include<iostream>
using namespace std;
int main()
{
int a1[20],a2[20],intersec[40],k=0,num,flag=0;
cout<<"How many elements to be stored (max 20) : ";
cin>>num;
cout<<"Enter elements of array a1 : ";
for(int i=0;i<num;i++)
cin>>a1[i];
cout<<"Enter elements of array a2 : ";
for(int i=0;i<num;i++)
cin>>a2[i];
for(int i=0;i<num;i++)
{
for(int y=0;y<num;y++)
if(a1[i]==a2[y])
intersec[k++]=a1[i];
}
cout<<"a1 intersection a2 : ";
for(int i=0;i<k;i++)
{
for(int y=i+1;y<k;y++)
if(intersec[i]==intersec[y])
flag=1;
if(flag==0)
cout<<intersec[i]<<" ";
flag=0;
}
return 0;
}
using namespace std;
int main()
{
int a1[20],a2[20],intersec[40],k=0,num,flag=0;
cout<<"How many elements to be stored (max 20) : ";
cin>>num;
cout<<"Enter elements of array a1 : ";
for(int i=0;i<num;i++)
cin>>a1[i];
cout<<"Enter elements of array a2 : ";
for(int i=0;i<num;i++)
cin>>a2[i];
for(int i=0;i<num;i++)
{
for(int y=0;y<num;y++)
if(a1[i]==a2[y])
intersec[k++]=a1[i];
}
cout<<"a1 intersection a2 : ";
for(int i=0;i<k;i++)
{
for(int y=i+1;y<k;y++)
if(intersec[i]==intersec[y])
flag=1;
if(flag==0)
cout<<intersec[i]<<" ";
flag=0;
}
return 0;
}
No comments:
Post a Comment