The Programming Project: Set intersection
Showing posts with label Set intersection. Show all posts
Showing posts with label Set intersection. Show all posts

Monday, September 16, 2013

Intersection of Sets



To find intersection of two sets through C

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
void inter_set(int *s1,int*s2,int n,int m);
int main()
{
int n,m,i;
int *s1,*s2;
printf("\n Enter the number of elements in the sets:");
scanf("%d %d",&n,&m);
s1=(int *)malloc(n*sizeof(int));
s2=(int *)malloc(m*sizeof(int));
printf("\n Enter the elements of the set 1:");
for(i=0;i<n;i++)
{
printf("\n Enter the element %d:",i+1);
scanf("%d",&s1[i]);
}
printf("\n Enter the elements of the set 2:");
for(i=0;i<m;i++)
{
printf("\n Enter the element %d:",i+1);
scanf("%d",&s2[i]);
}
inter_set(s1,s2,n,m);
return 0;
}
void inter_set(int *s1,int*s2,int n,int m)
{
int *s,i=0,j,k;
int flag=0;
s=(int *)malloc((m<n ? m: n)*sizeof(int));
for(j=0;j<m;j++)
{
for(k=0;k<n;k++)
{
if(s2[j]==s1[k])
{
flag=1;
break;
}
}

if(flag==1)
{
s[i]=s2[j];
         i++;
flag=0;
}
 if(flag==0)
continue;
 }
 if(i==0)
printf("\n Intersection is Null:");
else
{
  printf("\n Intersection of the entered sets is:");
  printf("\n { ");
  for(j=0;j<i-1;j++)
printf(" %d,",s[j]);
  printf(" %d }\n ",s[i-1]);
}


return;
}