Copying an Integer Array – CSKC
Sign In

Search

Code Learning #CPP#3091    siteicon   siteicon  

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

TC++ #3091

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

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];


Share

Created: 27-Jan-2018 22:29 | Updated: 27-Jan-2018 22:35|