Merge Two Arrays

Merge Two Arrays in C++ (5 Programs)

BeginnerTopic: Array Operations Programs
Back

C++ Merge Two 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 arr1[] = {1, 2, 3};
    int arr2[] = {4, 5, 6};
    int n1 = 3, n2 = 3;
    
    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
Merged array: 1 2 3 4 5 6

Understanding Merge Two Arrays

This program demonstrates 5 different methods to merge two arrays: simple concatenation, using vectors, using copy() algorithm, using memcpy(), and using dynamic arrays.

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 Two Arrays

This C++ program is part of the "Array Operations 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