Array data structure is used to store homogeneous data in contiguous memory Locations access them in a sequential manner. Arrays are linear data structures, so Basic operations on arrays can be performed in linear time. In this article we will learn how Copy elements from one array to another new array in C.
Since array elements are homogeneous, the new array will have the same type. After creation Another array of the same size, we just copy the elements from the first array to the second array one. Let’s see the algorithm and C implementation for better understanding.
#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[0] ); cout << "Given array: "; display(arr, n); int newArray[n] = {0}; solve( arr, newArray, n ); cout << "\nArray After copying: "; display(newArray, n); }
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,
Copying elements from an array is one of the simplest tasks in array-based programming. We create a new array whose size is at least equal to the size of the given array. Then we traverse Iterates through each index of the given array and copies the elements in the given array to the new array In large quantities. Since there is no need to traverse the array multiple times, the operation can be Execute in linear time, so the asymptotic upper limit is O(n). The same goes for space utilization The new array requires the same amount of space. Copying requires O(n) amount of space Elements are added to the new array.
The above is the detailed content of C++ program: Copy all elements of one array to another array. For more information, please follow other related articles on the PHP Chinese website!