# C++ Program to Copy All the Elements of One Array to Another Array

The array data structures are used to store homogeneous data in a consecutive memory location to access them in a sequential manner. Arrays are linear data structure so that the basic operations on array can be performed in linear time. In this article we will see how to copy elements from one array to another new array in C++.

The new array will be of same type since array elements are homogeneous. After creating another array of same size, we simply copy the elements from first array to the second one by one. Let us see the algorithm and the C++ implementation for a better understanding.

### Algorithm

• read array A and its size n as input
• Create empty array B of size same as A, which is n
• for i ranging from 0 to n-1, do
• B[ i ] := A[ i ]
• end for

### Example

#include <iostream>
using namespace std;
void display( int arr[], int n ){
for ( int i = 0; i < n; i++ ) {
cout << arr[i] << ", ";
}
}
void solve( int arr[], int newArr[], int n ){
int i;
for ( i = 0; i < n; i++ ) {
newArr[ i ] = arr [ i ];
}
}
int main(){
int arr[] = {9, 15, 24, 28, 20, 6, 12, 78, 2, 12, 78, 44, 25, 115, 255, 14, 96, 84 };
int n = sizeof( arr ) / sizeof( arr );
cout << "Given array: ";
display(arr, n);
int newArray[n] = {0};
solve( arr, newArray, n );
cout << "\nArray After copying: ";
display(newArray, n);
}


### Output

Given array: 9, 15, 24, 28, 20, 6, 12, 78, 2, 12, 78, 44, 25, 115, 255, 14, 96, 84,
Array After copying: 9, 15, 24, 28, 20, 6, 12, 78, 2, 12, 78, 44, 25, 115, 255, 14, 96, 84,


## Conclusion

Copying elements from one array is one of the simplest task in array based programming. We create a new array whose size is at least the size of the given array. Then we traverse through each index of the given array then copy elements from the given array to the new array. Since it does not require to traverse the array more than once, the operation can be performed in linear time, so the asymptotic upper bound is O(n). For the space usage also, it needs same amount of space for the new array. It takes O(n) amount of space to copy elements to the new array.