C PROGRAM FOR UNION OF SETS
In set theory, the set containing every element in a collection is the union of all its sets. It is one of the fundamental operations that allow sets to be joined together and connected to one another.
When two more sets are combined, a new set is created that comprises every element from each of the sets that were engaged in the union operation, but no element is repeated in the set.
Example:
If there are two sets A and B consisting of m and n number of elements;
A= {1, 5, 9, 7, 8}
B= {2, 0, 3, 4}
Then Set C contains the elements of both the sets which is known as UNION SET of the Set A and Set B.
C= {1, 5, 9, 7, 8, 2, 0, 3, 4}
Implementing Union Operation in C program:
#include<stdio.h>
void main()
{
int p[10],q[10],i,r[10],j,k=0,n1,n2;
// taking input into set p
printf("Enter number of elements of set P\n");
scanf("%d",&n1);
printf("Enter the elements of set P \n");
for(i=0;i<n1;i++)
scanf("%d",&p[i]);
// taking input into set Q
printf("Enter number of elements of set Q\n");
scanf("%d",&n2);
printf("Enter the elements of set Q \n");
for(i=0;i<n2;i++)
scanf("%d",&q[i]);
// logic for calculate union
// copying the elements of set Q in set R
for(i=0;i<n1;i++)
{
// We check to see whether any values are repeated because repeated elements are not permitted.
for(j=0;j<k;j++)
{
if(r[j]==p[i])
break;
}
if(j==k) //if not repeated then store it in R
{
r[k]=p[i];
k++;
}
}
// Copying of elements of Set P into Set R
for(i=0;i<n2;i++)
{
// check which element is repeated
for(j=0;j<k;j++)
{
if(r[j]==q[i])
break;
}
if(j==k) // Put the element in set R if it isn't repeated.
{
r[k]=q[i];
k++;
}
}
// Displaying Union of both P and Q
printf("The Union of the sets P and Q is:-\n");
for(i=0;i<k;i++)
printf("%d ",r[i]);
}
OUTPUT:
![C PROGRAM FOR UNION OF SETS](https://static.tutorialandexample.com/c/c-program-for-union-of-sets1.png)