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.

Practical Learning Notes for Merge Arrays

This C++ program is part of the "Array Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents