Merge Arrays

Program to merge two arrays into one

BeginnerTopic: Array Programs
Back

C++ Merge Arrays Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    int n1, n2;
    
    cout << "Enter size of first array: ";
    cin >> n1;
    int arr1[n1];
    cout << "Enter " << n1 << " elements: ";
    for (int i = 0; i < n1; i++) {
        cin >> arr1[i];
    }
    
    cout << "Enter size of second array: ";
    cin >> n2;
    int arr2[n2];
    cout << "Enter " << n2 << " elements: ";
    for (int i = 0; i < n2; i++) {
        cin >> arr2[i];
    }
    
    int merged[n1 + n2];
    
    // Copy first array
    for (int i = 0; i < n1; i++) {
        merged[i] = arr1[i];
    }
    
    // Copy second array
    for (int i = 0; i < n2; i++) {
        merged[n1 + i] = arr2[i];
    }
    
    cout << "Merged array: ";
    for (int i = 0; i < n1 + n2; i++) {
        cout << merged[i] << " ";
    }
    cout << endl;
    
    return 0;
}
Output
Enter size of first array: 3
Enter 3 elements: 1 2 3
Enter size of second array: 3
Enter 3 elements: 4 5 6
Merged array: 1 2 3 4 5 6

Understanding Merge Arrays

Merging arrays involves combining two arrays into one. We create a new array of size (n1 + n2). First, we copy all elements from the first array, then copy all elements from the second array starting at index n1.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents