How to find intersection of two sets A and B using C programming?
Feb 14, 2021
Algorithm:
- Read the elements of the set A and B.
- Initialize intersection array I as empty.
- Do the following for every element x of array A.
- 1. If x is present in array B, then copy x to array I .
- Return I.
Source Code:
#include<stdio.h>
#include<math.h>
void main()
{
int i,k=0, A[10], B[10], I[25], j, n, m, f=0;
printf(“\n How many elements in SET A:”);
scanf(“%d”,&n);
printf(“\n Enter SET A elements”);
for(i=0;i<n;i++)
{
scanf(“%d”,&A[i]);
}
printf(“\n How many elements in set B:”);
scanf(“%d”,&m );
printf(“\n Enter SET B elements”);
for(i=0; i<m; i++)
{
scanf(“%d”,&B[i]);
}
for(j=0; j<n; j++)
{
for(i=0; i<m ; i++)
{
if(B[i]==A[j])
break;
}
if (i!=m )
{
I [f]=B[i];
f++;
}
}
printf(“\n The intersection set A and B is :{“);
for(i=0;i<f;i++)
printf(“%d”,I[i]);
printf(“}”);
}
Output: