Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

IN C++: Write a program to merge two integer arrays into a third array with alte

ID: 674226 • Letter: I

Question

IN C++: Write a program to merge two integer arrays into a third array with alternate elements from the first and second array respectively.

Your program should do the following:

a. Input size of 2 arrays

b. Input the array elements

c. Write a loop structure to copy elements into a third array in an alternate fashion

d. Print the merged array

Note: If one array is extinguished, continue to copy the remaining elements of the other array

Example: size1 = 3

size2 = 4

array1 = {2,3,5}

array2 = {1,8,3,0}

array3 = {2,1,3,8,5,3,0}

output 2138530

Explanation / Answer

#include <iostream>

#include <string>

using namespace std;

int main()

{

int arr1,arr2,arr3;

  

cout << "Input the size of array 1 : ";

cin >> arr1;

  

cout << "Input the size of array 2 : ";

cin >> arr2;

  

arr3 = arr1+arr2;

  

int array1[arr1],array2[arr2],array3[arr3];

  

cout << "Inputting array1 ";

for(int i=0;i<arr1;i++)

{

cout << "Input " << i+1 <<" number of array1 : ";

cin >> array1[i];

  

}

  

cout << "Inputting array2 ";

for(int i=0;i<arr2;i++)

{

cout << "Input " << i+1 <<" number of array2 : ";

cin >> array2[i];

  

}

  

cout << "Merging two arrays : ";

  

int iterate;

  

if(arr1<=arr2)

iterate = arr1;

else

iterate = arr2;

  

int i=0,k = 0;

while(i<iterate)

{

array3[k] = array1[i];

array3[k+1] = array2[i];

  

i++;

k = k+2;

}

  

if(i!=arr1)

{

while(i<arr1)

{

array3[k] = array1[i];

i++;

k++;

}

}

  

if(i!=arr2)

{

while(i<arr2)

{

array3[k] = array2[i];

i++;

k++;

}

}

  

cout << "Merged array is : ";

  

for(int i=0;i<arr3;i++)

cout << array3[i] << " " ;

  

return 0;

}