Program to find the union of two sorted arrays in CPP (C plus plus)

Program to find the union of two sorted arrays in CPP (C plus plus)

In this tutorial, we will learn about Program to find the union of two sorted arrays in CPP (C plus plus).

#include<iostream>
 
using namespace std;
 
int main()
{    
	int i;
	int j;
	int l;
	int no;
	int m;
	int array[20];
	int array1[20];
	int array2[40];
    
    cout<<"Please enter the size of first array: ";
    cin>>no;
    
    cout<<"Please enter the values of first array in ascending order: "<<endl;
    
    for(i=0;i<no;++i){
        cin>>array[i];
    }
    
    cout<<endl<<"Please enter size of second array: ";
    cin>>m;
    
    cout<<"Please enter the values of second array in ascending order: "<<endl;
    
    for(i=0;i<m;++i){
        cin>>array1[i];
    }
    
    for(i=0,j=0,l=0;i<no&&j<m;){
        if(array[i]<array1[j]){
            array2[l]=array[i];
            i++;
            l++;
        }
        
        else if(array[i]>array1[j]){
            array2[l]=array1[j];
            j++;
            l++;
        }
        
        else{
            array2[l]=array[i];
            i++;
            j++;
            l++;
        }
    }
    
    if(i<no){
        for(;i<no;++i){
            array2[l]=array[i];
            l++;
        }
    }
    
    else if(j<m){
        for(;j<m;++j){
            array2[l]=array1[j];
            l++;
        }
    }
    
    cout<<endl<<"The union of two arrays is: "<<endl;
    
    for(i=0;i<l;++i){
        cout<<array2[i]<<" ";
    }
 
    return 0;
}

Output:

Program to find the union of two sorted arrays in CPP (C plus plus)
Program to find the union of two sorted arrays in CPP (C plus plus)

 

Prof.Fazal Rehman Shamil (Available for Professional Discussions)
1. Message on Facebook page for discussions,
2. Video lectures on Youtube
3. Email is only for Advertisement/business enquiries.