How to merge two arrays in C++

In this problem, we will learn how to merge two arrays in C++ programming. You have to ask the user to enter the array 1 size and elements then size of the second array and elements to merge both the array and store the merged result in the third array.

So to merge two arrays, start adding the element of the first array to the third array, after this start adding the elements of the second array to the third array.

Problem Description:

In this problem, we have to take two such arrays and merge them into one. How? , you ask. Well, we all know that array is a non-dynamic data type ( the storage allocated to it cannot be changed during program execution.) So how are we gonna reallocate the size of the merged array? The answer is simple. We don’t. We take a third array having double the size of the arrays so that both of them can fit in it. And then we copy both the arrays one by one to the third array.

Algorithm to merge two arrays :

  1. At first, create two arrays of the required length.
  2. Create a third array that has the combined size of the first and second array.
  3. Copy the elements of the first array to the third array.
  4. Copy the elements of the second array to the third array. (Note: The elements should be placed after the last position, not from the first in the third array).

Examples:

Input : Array 1= 1 2 3 4 5 6 
        Array 2= 78 84 32 34 33 
Output : Array 3= 1 2 3 4 5 6 78 84 32 34 33

Input : Array 1= 34 234 36 65 35 324 23 23 43
        Array 2= 234 234 25 4 645 7456 74 5
Output : Array 3= 34 234 36 65 35 324 23 23 43 234 234 25 4 645 7456 74 5

Code to merge two arrays in C++:

#include<iostream>
using namespace std;
int main()
{
 
  int frstarr[50],scndarr[50], fstsize, scndsize, size, i, j, k, mergarr[100];
  cout<<"Enter Array 1 Size : ";
  cin>>fstsize;
  cout<<"Enter Array 1 Elements : ";
  for(i=0; i<fstsize; i++)
  {
    cin>>frstarr[i];
                      mergarr[i]=frstarr[i];
  }
  cout<<"Enter Array 2 Size : ";
  cin>>scndsize;
  cout<<"Enter Array 2 Elements : ";
  for(i=0; i<scndsize; i++)
  {
    cin>>scndarr[i];
  }
  size=fstsize+scndsize;
  for(i=0, k=fstsize; k<size && i<scndsize; i++, k++)
  {
    mergarr[k]=scndarr[i];
  }
  cout<<"Now the new array after merging is :\n";
  for(i=0; i<size; i++)
  {
    cout<<mergarr[i]<<"  ";
  }

}

The output of the above program:

 

merge two arrays in C++

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *