C++ Program to split an array into two arrays [DEVCPP/GCC]


PROBLEM

We have to split an array into two arrays in an efficient way as described in the image below.


STEPS

1. Input the elements of an array C (which is to be biparted).

2. Initialize the index variable i and j with 0.

3. Assign the value at jth index of array C to ith index of array A and the value at (j+1)th index of array C to ith index of array B.

4. Increment i by 1 and j by 2.

5. Repeat step 3-4 until j<(size of the composite array), Here 8.

PROGRAM

//Program to split an array into two arrays (in an efficient way)

# include<iostream>

using namespace std;

int main()
{

int a[4],b[4],c[8],i,j;
cout<<"ENTER THE ELEMENTS OF COMPOSITE ARRAY:\n";
 
for(i=0; i<8 ;i++)            //Loop for input
{
cout<<"c["<<i<<"]=";
cin>>c[i];
}
cout<<endl;

for(i=0,j=0 ; j<8 ; i++,j+=2)
{
a[i]=c[j];
b[i]=c[j+1];
}

cout<<"\nPRINT THE ELEMENTS OF ARRAY1:\n";
for(i=0; i<4 ;i++)            //Loop for output
{
cout<<"b["<<i<<"]=";
cout<<b[i]<<endl;
}

cout<<"\nPRINT THE ELEMENTS OF ARRAY2:\n";
for(i=0; i<4 ;i++)            //Loop for output
{
cout<<"a["<<i<<"]=";
cout<<a[i]<<endl;
}

return 0;
}

OUTPUT

C++ Program to split an array into two arrays with output

Share this

Related Posts

FIND US ON FACEBOOK!