Finding if Arrays are disjoint or not using C

Finding if Arrays are disjoint or not

Here we will try to find if two arrays are disjoint or not. If there is not element of array X is found in array X then array X and array Y are disjoint.  two sets are said to be disjoint sets if they have no element in common. Equivalently, two disjoint sets are sets whose intersection is the empty set. For example, {3, 6, 9} and {4, 5, 8} are disjoint sets, while {1, 2, 3} and {3, 4, 5} are not disjoint.

 

C Program for Finding if Arrays are disjoint or not

Algorithm

  • Start.
  • Use two for loops.
  • Start traversing the element of the array array X using the first loop.
  • Use the second loop to check following condition
  • If the elements in array Y are found in array X.
  • If at least one element of array Y is found in array X.
  • Return false.
  • Else return true.

C Code to find if Arrays are disjoint or not

#include <stdio.h>
#include <stdlib.h>
int disjoint(int arrayX[], int arrayY[], int K, int k){
int a,A;
for(a = 0;a<K;a++){
for(A=0;A<k;A++){
if(arrayX[a] == arrayY[A])
return -1;
}
}
return 1;
}

  int main(){
     int k,K;
     printf("First Array Size- ");
     scanf("%d",&K);
     int arrayX[K];
     int a;
     printf("Elements- ");
     for(a=0;a<K;a++){
         scanf("%d",&arrayX[a]);
      }
      printf("Second Array Size- ");
      scanf("%d",&k);
       int arrayY[k];
       printf("Elements- ");
      for(a=0;a<k;a++){
         scanf("%d",&arrayY[a]);
       }
       int NEW = disjoint(arrayX,arrayY,K,k);
       if(NEW == -1)
           printf("The arrays are not disjoint\n");
       else
           printf("The arrays are disjoint\n");
       return 0;
 }
Input:

First Array Size- 6
Elements- 9 6 3 4 5 8
Second Array Size- 3
Elements- 9 7 2

Output:
The arrays are not disjoint

Comments