Programming Examples

Cpp program to merge two sorted arrays


Write a cpp program to merge two sorted arrays (ascending order)

Solution

#include<iostream>
using namespace std;
int main(){
    int arr[5],AR[3],rslt[10],i;
    cout<<"Enter the 5 elements of first array";
    for(i=0;i<5;i++)
    {
        cin>>arr[i];
    }
    cout<<"Enter the 3 elements of second array";
    for(i=0;i<3;i++)
    {
        cin>>AR[i];
    }
    int p1=0,p2=0,a=0;
    while(p1<5 && p2<3)
    {
        if(arr[p1]<=AR[p2])
        {
            rslt[a]=arr[p1];
            p1++;
        }
        else
        {
            rslt[a]=AR[p2];
            p2++;   
        }
        a++;
    }
    while(p1<5)
    {
        rslt[a]=arr[p1];
        p1++;
        a++;
    }
    while(p2<3)
    {
        rslt[a]=arr[p1];
        p1++;
        a++;
    }
    cout<<" SORTED ARRAY :"<<endl;
    for(i=0;i<8;i++)
    {
        cout<<rslt[i]<<" ";
    }
    return 0;
}
Output

Enter the 5 elements of first array 

12

24

36

48

60

Enter the 3 elements of second array

5

10

15

 SORTED ARRAY :

5 10 12 15 24 36 48 60

Latest Current Affairs 2024 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2024 Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz