Copying an Integer Array – Computer Sir Ki Class

Code Learning #CPP#3091

Copying an Integer Array

Demonstrating how an array can be copied to another array of same size by copying each member of the array.

Learning Objectives

• Copying an array to another array of same size by copying each member of the array.

Source Code

 #include using namespace std; int main() { int a1[5]={25,10,32,44,99}; int a2[5]; cout<<"Members of source array : "<

Run Output

``````Members of source array :
25 10 32 44 99
Members of destination array :
25 10 32 44 99``````

Code Understanding

int a1[5]={25,10,32,44,99}; //array a1 declared and initialised with 5 members
int a2[5];                                 //array a2 of same size as a1 declared.

cout<<“Members of source array : “<<endl;
for(int i=0;i<5;i++) cout<<a1[i]<<” “;
this loop shows members of array a1 by simply displaying member at each index.

for(int i=0;i<5;i++) a2[i]=a1[i];
This loop does the copy work by copying each member of array a1 to array a2 by using command  a2[i]=a1[i]

cout<<endl<<“Members of destination array : “<<endl;
for(int i=0;i<5;i++) cout<<a2[i]<<” “;
This loop displays the copied array

Notes

• This program will work well with any other type of data type as well.
• After c++11 you have another direct method of creating a copied array as follows.
array<int,4> A = {10,20,30,40};
array<int,4> B = A;

Common Errors

• Student some time write copy statement as a1[i]=a2[i]. This is incorrect. Remember always the right side is assigned to left hand side. So it should definitely be a2[i]=a1[i];

sunmitra| Created: 27-Jan-2018 | Updated: 27-Jan-2018|

×