Open In App

Concatenate Two int Arrays into One Larger Array in C++

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

In C++, an array is a linear data structure we use to store data in contiguous order. It helps to efficiently access any element in O(1) time complexity using its index. In this article, we will learn how to concatenate two integer arrays into one larger array in C++.

Example:

Input: 
arr1: {1, 2, 3, 4}
arr2: {5, ,6, 7, 8}

Output:
res: {1, 2, 3, 4, 5, 6, 7, 8}

Concatenate Two int Arrays into One Larger Array in C++

To concatenate two Int arrays, we can simply calculate the size of both arrays and we can make a larger array of sizes equal to the sum of both sizes. After that, we can copy the first array into a larger array and then the second array into a larger array.

Approach

  • Find the size of the first and second array
  • Make an array of size equal to the: size of the first array + the size of the second array
  • Copy elements of the first array into the larger array
  • Copy elements of the second array into the larger array

C++ Program to Concatenate Two int Arrays into One Larger Array

C++




// C++ Program to illustrate how to concatenate two int
// arrays into one larger array
#include <iostream>
using namespace std;
  
void concatenate(int* arr1, int* arr2, int n, int m)
{
    int k = n + m;
    // Made Array of size equal to the size of first Array +
    // Size of second Array
    int arr3[k];
    // Copy element of first array into the larger array
    for (int i = 0; i < n; i++) {
        arr3[i] = arr1[i];
    }
    // Copy element of second array into the larger array
    for (int i = 0; i < m; i++) {
        arr3[n + i] = arr2[i];
    }
    // Printing element of larger array
    for (int i = 0; i < k; i++) {
        cout << arr3[i] << " ";
    }
}
// Driver Code
int main()
{
    int arr1[] = { 1, 2, 3, 4, 5 };
    int arr2[] = { 6, 7, 8, 9, 10, 11, 12, 13, 14 };
  
    // Size of first array
    int n = sizeof(arr1) / sizeof(arr1[0]);
  
    // Size of second array
    int m = sizeof(arr2) / sizeof(arr2[0]);
  
    concatenate(arr1, arr2, n, m);
  
    return 0;
}


Output

1 2 3 4 5 6 7 8 9 10 11 12 13 14 

Time Complexity: O(M + M), where N is the size of first array and M is the size of second array
Auxiliary Space: O(N + M)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads