Concatenate Two int Arrays into One Larger Array in C++
Last Updated :
06 Mar, 2024
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++
#include <iostream>
using namespace std;
void concatenate( int * arr1, int * arr2, int n, int m)
{
int k = n + m;
int arr3[k];
for ( int i = 0; i < n; i++) {
arr3[i] = arr1[i];
}
for ( int i = 0; i < m; i++) {
arr3[n + i] = arr2[i];
}
for ( int i = 0; i < k; i++) {
cout << arr3[i] << " " ;
}
}
int main()
{
int arr1[] = { 1, 2, 3, 4, 5 };
int arr2[] = { 6, 7, 8, 9, 10, 11, 12, 13, 14 };
int n = sizeof (arr1) / sizeof (arr1[0]);
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)
Share your thoughts in the comments
Please Login to comment...