Open In App

How to Concatenate Two Arrays in C++?

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, arrays store a fixed number of elements of the same type in contiguous memory locations. In this article, we will learn how to concatenate two arrays in C++.

Example:

Input: 
myArray1={10, 30, 40}
myArray2 ={20, 50, 60}

Output:
Concatenated Array: 10 30 40 20 50 60

Concatenate Two Arrays in One Larger Array in C++

We can concatenate two arrays into one larger array by creating a new array and copying the elements from the original arrays into it by iterating over the elements of the original arrays.

C++ Program to Concatenate Two Arrays

The below program demonstrates how we can concatenate two arrays into a single large array in C++.

C++
// C++ program to illustrate how to concatenate two arrays
// into a single one
#include <iostream>

using namespace std;

int main()
{
    // Define the input arrays
    int arr1[] = { 10, 30, 40 };
    int arr2[] = { 20, 50, 60 };

    // Determine the size of the arrays
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
    int n2 = sizeof(arr2) / sizeof(arr2[0]);

    // Create a new array to hold the concatenated elements
    int arr3[n1 + n2];

    // Copy the elements from the first array
    for (int i = 0; i < n1; i++)
        arr3[i] = arr1[i];

    // Copy the elements from the second array
    for (int i = 0; i < n2; i++)
        arr3[n1 + i] = arr2[i];

    // Print the concatenated array
    cout << "Concatenated Array: ";
    for (int i = 0; i < n1 + n2; i++)
        cout << arr3[i] << " ";
    cout << endl;

    return 0;
}

Output
Concatenated Array: 10 30 40 20 50 60 

Time Complexity: O(N+M), here N and M are the lengths of both the arrays.
Auxiliary Space: O(N+M)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads