Determine Array is a subset of another array or not using C

Determine Array is a subset of another array in C

Determine Array is a subset of another array or not

Here we will try to find if a given array is subset of another array or not. If each and every elements of array Y are found in array X, then array Y is said to be a subset of array X. We can use two loops to traverse the array using the outer loop.  and using second loop check condition that if all the elements in array Y are present in array X then Y is subarray of X

Algorithm

  • To check if Y is subset of  X or not, take two loops.
  • Start traversing the array  X and Y using the first loop.
  • Now, use the second loop, check if the elements in array Y are present in array X.
  • If all the elements of array Y are found in array X.
  • Return true.
  • If all the elements of array Y are not found in array X
  • Return false.

C Code to find if Array is a subset of another array or not

 

#include<stdio.h>
#include<stdbool. h>

bool isSubset(int arrayX[], int arrayY[], int a, int b) {
     int x = 0;
     int y = 0;
     for (x = 0; x < b; x++) {
         for (y = 0; y < a; y++) {
            if (arrayY[x] == arrayX[y])
               break;
           }

           if (y == a)
           return 0;
        }

        return 1;
     }

int main() {
    int a, b;
    printf("Enter the size of first array : ");
    scanf("%d", & a);
    int arrayX[a];
    int x;
    printf("Enter elements of first array : ");
    for (x = 0; x < a; x++) {
       scanf("%d", & arrayX[x]);
    }
     printf("Enter the size of second array : ");
     scanf("%d", & b);
     int arrayY[b];
     int y;
    printf("Enter elements of second array: ");
    for (x = 0; x < b; x++) {
       scanf("%d", & arrayY[x]);
    }

    if (isSubset(arrayX, arrayY, a, b))
        printf("arrY is a subset of arrX\n ");
    else
       printf("arrY is NOT a subset of arrX\n");

     getchar();
     return 0;
}
Input:

Enter the size of first array : 6
Enter elements of first array : 9 6 3 2 1 4
Enter the size of second array : 3
Enter elements of second array: 9 8 6

Output:
arrY is NOT a subset of arrX

Comments