Thursday 26 June 2014

C++ program to merge two arrays


Here is a C++ program to merge two arrays


 SOURCE CODE OUTPUT
#include<iostream>
using namespace std;
int main()
{
    int i=0,j=0,k=0,a1[20],a2[20],a3[40],num;
    cout<<"How many elements to be stored (max 20) : ";
    cin>>num;
    cout<<"Enter elements of array a1 : ";
    for(int i=0;i<num;i++)
        cin>>a1[i];
    cout<<"Enter elements of array a2 : ";
    for(int i=0;i<num;i++)
        cin>>a2[i];
    while(k<2*num)
    {
        if(a1[i]<a2[j])
        {
            a3[k]=a1[i];
            i++,k++;
        }
        if(i>=num)
          while(j<num)
          {
              a3[k]=a2[j];
              j++,k++;
          }
        if(a1[i]>a2[j])
        {
            a3[k]=a2[j];
            j++,k++;
        }
        if(j>=num)
          while(i<num)
          {
              a3[k]=a1[i];
              i++,k++;
          }
    }
    cout<<"After merging of two arrays : ";
    for(int i=0;i<2*num;i++)
        cout<<a3[i]<<" ";
    return 0;
}

Any questions regarding to program please write in comments.

No comments:

Post a Comment