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();
}
#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();
}
can a set have duplicate elements say
ReplyDeletex={5,3,5,7}
y={3,5,3,8}
This program is wrong?
ReplyDeleteCorrected Program
ReplyDelete#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++;
}
}
}
this is showing wrong output repeating values
DeleteIt's correct but when you enter inputs for union like a={1,1,2,2} B={2,3,4,5}
ReplyDeleteThe output comes like this c={1,1,2,2,3,4,5}