Thursday, 20 February 2014

Suppose that two arrays, “a” and “b”, contain sets of integers. Neither of these sets contains any duplication. Write a C function to find out the union of these two sets. For example, if “a” is {2, 7, 1, 5} and “b” is {9, 2, 8, 5} then their union is {2, 7, 1, 5, 9, 8}.

#include<stdio.h>
main()
{   
    int a[100],b[100],u[200],n1,n2,i,j,k,f;
    printf("\nEnter number of terms of the first set=");
    scanf("%d",&n1);
    printf("\nEnter the elements of the first set=");
    for(i=0;i<n1;i++)
    {
        scanf("%d",&a[i]);
    }
   
   
    printf("\nEnter number of terms of the second set=");
    scanf("%d",&n2);
    printf("\nEnter the elements of the second set=");
    for(i=0;i<n2;i++)
    {
        scanf("%d",&b[i]);
    }
    printf("\nThe elements of the first set=");
    for(i=0;i<n1;i++)
    {
        printf("%d ",a[i]);
    }
    printf("\nThe elements of the second set=");
    for(i=0;i<n2;i++)
    {
        printf("%d ",b[i]);
    }
   
    for(i=0;i<n1;i++)
    {
        u[i]=a[i];
    }
   
    for(j=0;j<n2;j++)
    {
        f=0;
        for(k=0;k<n1;k++)
        {
            if(a[k]==b[j])
            {
                f=1;
                break;
            }
        }
        if(f==0)
            u[i++]=b[j];
    }
    printf("\nThe union=");
    for(j=0;j<i;j++)
    {
        printf("%d ",u[j]);
    }   
}

No comments:

Post a Comment