WAP in C++ & Python for the Union of Two Arrays

Posted in

WAP in C++ & Python for the Union of Two Arrays

Vinay Khatri
Last updated on June 8, 2022

    Here in this program, we will code to combine two Array in a sorted manner. In this program, we will ask the user to enter elements for two arrays in ascending order and combine both arrays elements and store them in a new array. The new array which would be a union of user two entered arrays must be sorted.

    C Program for the Sorted Union of Two Arrays

    #include<stdio.h>
    #include<conio.h>
    #include<iostream.h>
    void main()
    {
    clrscr();
    int a[50],b[50],c[100],k,j,na,nb;
    cout<<"How many elements you want to enter in Array A and B?\n";
    cin>>na>>nb;
    cout<<"Enter the elements of Array A in ascending order\n";
    for(int i=0;i<na;i++)
        cin>>a[i] ;
    cout<<"Now Enter elements of Array B in ascending order\n";
    for(i=0;i<nb;i++)
        cin>>b[i];
    cout<<"The Union of the two arrays is \n" ;
    k=0;
    j=0;
    for(i=0;i<na+nb;i++)
        {
        if(a[k]<b[j])
        {          c[i] = a[k];
                    k++;
         }
        else if(a[k]>b[j])
                    {
                    c[i]=b[j];
                    j++;
                    }
        else if(k==na)
          {
          c[i]=b[j];
          j++;
          }
        else if(j==nb)
         {
         c[i]=a[k];
         k++;
         }
       }
    for(i=0;i<na+nb;i++)
        cout<<c[i]<<"  ";
    getch();
    }

    Output:

    How many elements you want to enter in Array A and B
    
    4
    5
    
    Enter the elements of Array A in ascending order
    
    3
    4
    7
    9
    
    Enter the elements of Array B in ascending order
    
    5
    8
    11
    12
    16
    
    The Union of the two arrays is
    
    3 4 5 7 8 9 11 12 16

    Python Program for the sorted union of two Arrays

    a=[]
    b=[]
    c=[]
    
    na, nb =list(map(int,input("How many elements you want to enter in Array A and B\n").split()))
    print("Enter the elements of Array A in ascending order")
    a= [int(input()) for i in range(na)]
    print("Enter the elements of Array B in ascending order")
    b=[int(input()) for i in range(nb)]
    c = sorted(a+b)
    print("The Union of the two arrays is ")
    for i in c:
        print(i,end=" ")

    Output: How many elements you want to enter in Array A and B 3 4 Enter the elements of Array A in ascending order 1 5 67 Enter the elements of Array B in ascending order 2 45 50 55 The Union of the two arrays is 1 2 5 45 50 55 67 People are also reading:

    Leave a Comment on this Post

    0 Comments