codescracker


c++

C++ Program to Merge Two Arrays



« Previous Program Next Program »


Merge Two Arrays in C++

To merge two arrays in C++ programming, you have to ask to the user to enter the array 1 size and elements then array 2 size and elements to merge both the array and store the merged result in the third array say merge[ ]. So to merge two array, start adding the element of first array to the third array (target array) after this start appending the elements of second array to the third array (target array) as shown here in the following program.

C++ Programming Code to Merge Two Arrays

Following C++ program ask to the user to enter array 1 and 2 size, then ask to enter array 1 and 2 elements, to merge or add to form new array, then display the result of the added array or merged array (Here we display the direct merged array). You can also sort the two array then merge or sort after merge. So to learn about sorting, here are the three techniques :

/* C++ Program - Merge Two Arrays */
		
#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	int arr1[50], arr2[50], size1, size2, size, i, j, k, merge[100];
	cout<<"Enter Array 1 Size : ";
	cin>>size1;
	cout<<"Enter Array 1 Elements : ";
	for(i=0; i<size1; i++)
	{
		cin>>arr1[i];
	}
	cout<<"Enter Array 2 Size : ";
	cin>>size2;
	cout<<"Enter Array 2 Elements : ";
	for(i=0; i<size2; i++)
	{
		cin>>arr2[i];
	}
	for(i=0; i<size1; i++)
	{
		merge[i]=arr1[i];
	}
	size=size1+size2;
	for(i=0, k=size1; k<size && i<size2; i++, k++)
	{
		merge[k]=arr2[i];
	}
	cout<<"Now the new array after merging is :\n";
	for(i=0; i<size; i++)
	{
		cout<<merge[i]<<" ";
	}
	getch();
}

When the above C++ program is compile and executed, it will produce the following result:

C++ program merge two array

Same Program in Other Language

You may like the same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test