C Program To Find Union & Intersection Of Two Array

How to write a C Program To Find Union & Intersection Of Two Array in C Programming Language ?


Solution For C Program :

/*C Program To Find Union & Intersection Of Two Array.*/

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char arr1[10],arr2[10],arr3[20],arr4[20],arr5[10];
/*If u want to use already initialized array then u can use code given below as comment & change according to this in code given ahead*/
//char arr1[10]={'b','a','l','j','i'},arr2[10]={'g','o','s','w','a','m','i'},arr3[20],arr4[20],arr5[10];
int i=0,m,n,j,temp,k=0,t;
clrscr();
printf("\tNOTE: Union and Intersection are defined for sets and in \n\t     set repeation of element is not done.\n\n");
printf("enter no of elements in first array:");
scanf("%d",&m);
fflush(stdin);
printf("\nenter elements of first array:\n");
for(i=0;i<m;i++)
    {
    scanf("%c",&arr1[i]);
    fflush(stdin);
    }arr1[i]='\0';
printf("enter no of elements in second array:");
scanf("%d",&n);
fflush(stdin);
printf("\nenter the elements of second array:\n");
for(i=0;i<n;i++)
    {
    scanf("%c",&arr2[i]);
    fflush(stdin);
    }arr2[i]='\0';

printf("\nEntered array is:\n\tarr1={");

for(i=0;i<m;i++)
    {
    printf("%c,",arr1[i]);
    arr3[k]=arr1[i];k++;    //merging in arr3
    }
    printf("}\n\tarr2={");
for(i=0;i<n;i++)
    {
    printf("%c,",arr2[i]);
    arr3[k]=arr2[i];k++;    //merging in arr3
    }arr3[k]='\0';
    printf("}\n");
    printf("\nMerged array: ");
puts(arr3);
/***************sorting starts here*/

printf("\nsorted array is:\n");
for(i=1;arr3[i]!='\0';i++)
    {
    for(j=1;arr3[j]!='\0';j++)
        {
        if(arr3[j-1]<arr3[j])
            {
            temp=arr3[j-1];
            arr3[j-1]=arr3[j];
            arr3[j]=temp;
            }
        }
    }
/***************sorting ends here*******/
printf("\n\tarr3={");
for(i=0;arr3[i]!='\0';i++)
    {
    printf("%c,",arr3[i]);
    }
    printf("}\n");

/*********Union starts here********/
k=1;
arr4[0]=arr3[0];
    for(j=0;arr3[j]!='\0';j++)
        {
        if(arr3[j]!=arr3[j+1])
            {
            arr4[k]=arr3[j+1];
            k++;
            }
        }
printf("\nUnion of two array: \n \narr4={");
for(i=0;arr4[i]!='\0';i++)
    {
    printf("%c,",arr4[i]);
    }
/*********Intersection starts here******/
printf("}\n\nIntersection of two array: \n\narr5={");
t=0;
for(j=0;arr3[j]!='\0';j++)
    {
    if(arr3[j]==arr3[j+1])
        {
        arr5[t]=arr3[j];
        t++;
        }
    }arr5[t]='\0';

for(i=0;arr5[i]!='\0';i++)
    {
    printf("%c,",arr5[i]);
    }printf("}");

getch();
}

You may also learn these C Program/Code :

C Program To Swap Two Numbers Without Using Third Variable


Learn More :