How to copy elements of one array to another in C++

This is a very simple and easy to understand topic where we will learn how to copy elements of one array to another in C++.

We all know about arrays. Those who don’t know about it. Arrays are just a collection of similar data types grouped. Like the names of your dogs or the names of flowers in your garden. No other data type can be accommodated in that specific array, for example, if you insert the name of your dogs in the array you were inserting the names of flowers, would it make any sense? Similarly, we cannot copy elements of one array into a different array. Suppose we create an array that contains integers, the array you would want to copy it’s elements should also be an integer array.

Both the arrays should:

  1. be of the same type.
  2. have the same length or the array in which you’ll copy should be larger.

Illustration :

If one of your arrays contains A={1,4,5,6,3,3,2,3,4,4} then the array you’ll copy should have B={1,4,5,6,3,3,2,3,4,4} after copying.

Procedure to copy elements of one array to another in C++

  1. Create an empty array.
  2. Insert the elements.
  3. Create a duplicate empty array of the same size.
  4. Start for i=0 to i=array length.
  5. newarray[i]=oldarray[i]
  6. end for

C++ program:

#include<iostream>
using namespace std;
int main()
{
        int initA[100],finA[100],i,size;
        cout<<"Input the size of the array : ";
        cin>>size;
        cout<<"Input the elements of the first array";
        for(i=0;i<size;i++)
        {
               cin>>initA[i];
        }
        for(i=0;i<size;i++)
        {
             finA[i]=initA[i];
        }
        cout<<"The final array is\n";
        for(i=0;i<size;i++)
               cout<<finA[i]<<" ";
        return 0;
}

The output of the above code:

copy elements of one array to another in C++

 

This is a very simple program. I tried my best to do it in the easiest way possible. Hope you like it. If you have any doubts, please comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *