C++ program to determine the array is a subset of another array


Array is a subset of another array

In this section we will determine the program to find if an array is a subset of another array which is discussed here. If all the elements of array 2 are found in array 1, then array 2 is said to be a subset of array 1.

Example

arr1 = {1,2,3,4,5}     arr2 = {3,4,5}

arr2 is a subset of arr1.

arr3 = {1,2,3,4,5} arr4 = {1,2,9}

arr4 is not a subset of arr3.

 

subset-or-not

Algorithm.

  1. Use two loops.
  2. Traverse the array using the outer loop.
  3. Using the inner loop, check if the elements in array 2 are present in array 1.
  4. If all the elements of array 2 are found in array 1, return true.
  5. Else, return false.

C++ Code:-

    
    #include<iostream>
    using namespace std;
    bool subset_arrays(int array1[], int array2[],int xint y){
        int i = 0;
        int j = 0;
        for (i = 0i < yi++){
            for (j = 0j < xj++){
                if(array2[i] == array1[j])
                    break;
            }

            if (j == x)
                return false;
        }

        return true;
    }        

    void main (String[] args){
        int x,y,i;
        int arr1[] = new int[10];
        int arr2[] = new int[10];
        cout<<\nEnter the size of array 1 : “;
        cin>>m;
        cout<<\nEnter the size of array 2 : “;
        cin>>n;
        cout<<\nInput the array 1 elements : “;
        for(i=0;i<y;i++){
            cin>>arr1[i];
        }
        cout<<\nInput the array 2 elements : “;
        for(i=0;i<x;i++){
            cin>>arr2[i];
        }
        if(subset_arrays(arr1,arr2,n,m))
            cout<<\nArray 2 is a subset of array “;
            else
            cout<<\nArray 2 is not a subset of array “;
    }


    
    output
    Enter size of Array 15
    Enter size of Array 23
    Input elements of array 11 2 3 4 5
    Input elements of array 23 4 5
    Array2 is a subset of Array1