C Program With Algorithm to Find Intersection of Two Given Sets - Curious CORP

Saturday, August 31, 2019

C Program With Algorithm to Find Intersection of Two Given Sets

If you have encountered sets in mathematics then you have also encountered with intersection of two sets. Although it is a mathematical concept, it can be implemented through making programs in C.

In this tutorial,  you will learn how you can make a C program that takes two sets and finds the intersection between them.

C Program With Algorithm to Find Intersection of Two Given Sets

Logic for Intersection of Two Sets

In mathematics, a set contains a number of elements. Intersection of two set means the listing the common elements from both the in the new set. 

For example,

set A={1,2,3,4,5,6}
set B={2,3,4,6,8,9}

from the above given sets, the Intersection of the two sets will be,

A(intersection)B = {2,3,4,6}

so, this is the logic which will be used to form a algorithm to make a program that can find intersection of two sets.

Source code of the C Program 


void main()
   int a[100],b[100],m,n,j,i,k;
   printf("Enter the first set size : \n");
   printf("Enter the first set : \n");
   printf("Enter the seconnd set size : \n");
   printf("Enter the second set : \n");
   printf(" The intersection set is : \n\n");

     printf("%d ",b[j]);

Explanation of Algorithm used in C program 

First For Loop
The first for loop is running from 0 to m-1

Second For Loop
The second for loop or the nested for loop is running from 0 to n-1

If Condition
The if condition is checking if the values of the two sets are equal.

In the first for loop with i and running from 0 to m-1 times is representing the first array or first set.

Similarly, the nested for loop with j is running from 0 to n-1 which represents the second array or second set.

Every time the first loop runs, the nested for loop runs n times for each run of the first loop. The if condition present in the second for loop checking if the the value of the i index of the array A is equal to the value of Array B with index j. So, every time with the first for loop run, one element of array A is being checked with every element of array B for equality and if the values are equal then the value is getting printed on the screen output which represents the intersection of the two sets.

No comments:

Post a Comment