Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: Union of Sets

Monday, September 16, 2013

Union of Sets


This C program finds the Union of two Sets (atleast one of is non-empty)
#Task- Apply recursion to the program below to find Union of finite number of sets

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
void union_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]);
}
union_set(s1,s2,n,m);
return 0;
}
void union_set(int *s1,int*s2,int n,int m)
{
int *s,i,j,k;
int flag=0;
s=(int *)malloc((m+n)*sizeof(int));
for(i=0;i<n;i++)
s[i]=s1[i];
for(j=0;j<m;j++)
{
for(k=0;k<n;k++)
{
if(s2[j]==s[k])
{
flag=1;
break;
}
}

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



}

No comments:

Post a Comment