Wednesday, 9 November 2022

Write a program in C to create two sets and perform the Intersectison operation on sets.

Logic

The intersection of two sets, A and B, which are subsets of the universal set U, is the set which consists of all those elements which are common to both A and B.

It is denoted by the “∩’ symbol. All those elements which belong to both A and B represent the intersection of A and B. Thus we can say that,

A ∩ B = {x : x ∈ A and x ∈ B}

For n sets A1, A2, A3, …, An, where all these sets are the subset of universal set U, the intersection is the set of all the elements which are common to all these n sets.

Depicting this pictorially, the shaded portion in the Venn diagram given below represents the intersection of the two sets A and B.

 



Program

#include<stdio.h>

int main()

{

    int a[100],b[100],c[100],n1,n2,n,k=0,i,j;

   

    // taking input of set A

   

    printf("Enter number of element of set A\n");

    scanf("%d",&n1);

    printf("Enter elements of set A\n");

    for(i=0;i<n1;i++)

      scanf("%d",&a[i]);

     

    // taking input set B

   

    printf("Enter number of element of set B\n");

    scanf("%d",&n2);

    printf("Enter elements of set B\n");

    for( i=0;i<n2;i++)

      scanf("%d",&b[i]);

     

    // Logic for intersection

   

    for( i=0;i<n1;i++)

    {

         for(j=0;j<n2;j++)

         {

            if(a[i]==b[j])

            {

                c[k]=a[i];

                k++;

            }

         }

       

    }

   

    // Printing the elements of intersection of set A and set B

    printf("intersection of set A and set B is:-\n");

    for(i=0;i<k;i++)

      printf("%d ",c[i]);

   

    return 0;

}

No comments:

Post a Comment