Write a ‘C’ program to find the union of two sets of integer(store in two arrays

#include<stdio.h>
#include<conio.h>
void main()
{
int i,k=0,x[10],y[10],c[25],j,n,n1,d[25],f=0;
clrscr();
printf("\n how many elements in SET 1:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n please enter the elements no %d",i+1);
scanf("%d",&x[i]);
}
printf("\n how many elements in set 2:");
scanf("%d",&n1);
for(i=0;i<n1;i++)
{
printf("\n please enter elements no %d",i+1);
scanf("%d",&y[i]);
}
for(i=0;i<n;i++)
{
c[k]=x[i];
k++;
}
for(i=0;i<n;i++)
{
for(j=0;j<n1;j++)
{
if(y[i]==x[j])
break;
}
if(j==n)
{
c[k]=y[i];
k++;
}
}
printf("\n the union set is:{");
for(i=0;i<k;i++)
printf("%d",c[i]);
printf("}\n");
for(j=0;j<n;j++)
{
for(i=0;i<n1;i++)
{
if(y[i]==x[j])
break;
}
if(i!=n1)
{
d[f]=y[i];
f++;
}
}
printf("\n the intersection set is :{");
for(i=0;i<f;i++)
printf("%d",d[i]);
printf("}");
getch();
}

3 comments:

  1. can a set have duplicate elements say
    x={5,3,5,7}
    y={3,5,3,8}

    ReplyDelete
  2. Corrected Program
    #include
    #include
    void main()
    {
    int i,k=0,a[10],b[10],c[25],j,n,m,d[25],f=0;
    clrscr();
    printf("\n how many elements in SET 1: ");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
    printf("\n please enter the elements no %d - ",i+1);
    scanf("%d",&a[i]);
    }
    printf("\n how many elements in set 2: ");
    scanf("%d",&m);
    for(i=0;i<m;i++)
    {
    printf("\n please enter elements no %d - ",i+1);
    scanf("%d",&b[i]);
    }
    for(i=0;i<n;i++)
    {
    c[k]=a[i];
    k++;
    }
    for(i=0;i<n;i++)
    {
    f=0;
    for(j=0;j<m;j++)
    {
    if(b[i]==c[j])
    {
    f=1;
    break;
    }
    }
    if(f==0)
    {
    c[k]=b[i];
    k++;
    }
    }
    printf("\n the union set is:{");
    for(i=0;i<k;i++)
    {
    printf("\t%d",c[i]);
    }
    printf("}\n");
    for(j=0;j<n;j++)
    {
    for(i=0;i<m;i++)
    {
    if(b[i]==a[j])
    break;
    }
    if(i!=m)
    {
    d[f]=b[i];
    f++;
    }
    }
    }

    ReplyDelete