### Ticker

6/recent/ticker-posts

# C program to find the intersection of two sets.

what is the intersection of two sets:-

intersection of two sets is the set in which only those element is present which are present in both set  A and set B.

if  A={1,2,3,4,1} and B={1,2,5,6} are two sets then intersection of A and B is:-

AB={1,2}

Program:-

#include<stdio.h>
int main()
{
int a[100],b[100],c[100],n1,n2,n,k=0,i,j;
// taking input of set A
printf("Enter number of element of set A\n");
scanf("%d",&n1);
printf("Enter elements of set A\n");
for(i=0;i<n1;i++)
scanf("%d",&a[i]);
// taking input set B
printf("Enter number of element of set B\n");
scanf("%d",&n2);
printf("Enter elements of set B\n");
for( i=0;i<n2;i++)
scanf("%d",&b[i]);
// Logic for intersection
for( i=0;i<n1;i++)
{
for(j=0;j<n2;j++)
{
if(a[i]==b[j])
{
c[k]=a[i];
k++;
}
}
}
// Printing the elements of intersection of set A and set B
printf("intersection of set A and set B is:-\n");
for(i=0;i<k;i++)
printf("%d ",c[i]);
return 0;
}

Output:-

Enter number of element of set A
3
Enter elements of set A
1 2 3
Enter number of element of set B
4
Enter elements of set B
1 1 3 4
intersection of set A and set B is:-
1 3

### 2 Comments

1. Can you explain how did you do it that your code run and the output is correct?

1. why not , first you have to know what is intersection of two sets . intersection means finding the elements which are presents in both sets.... so we have to compare the elements of the sets.. So take loop for the set 1 and another loop for set 2 .. after that you have to take a element from set one and compare with elements of set 2 if the element is equal to the any element of the set 2 then store it in the new array . after that at the end you just have to print this new array ...........that's all