Write a program in basic C++ to merge two integer arrays into a third array with
ID: 3758994 • Letter: W
Question
Write a program in basic C++ 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<time.h>
using namespace std;
int main() {
int arr1[3] = {1,2,3};
int arr2[6] = {4,5,6,7,8,9};
int len1 = 3;
int len2 = 4;
cout<<"Enter size 1: ";
cin>>len1;
cout<<"Enter size 2: ";
cin>>len2;
cout<<"Enter array 1: ";
for (int i=0; i<len1; i++) {
cin>>arr1[i];
}
cout<<"Enter array 2: ";
for (int i=0; i<len2; i++) {
cin>>arr2[i];
}
int len = len1+len2;
int *arr = (int *)malloc(sizeof(int)*(len));
int i=0;
int i1=0, i2=0;
while (i<len) {
if (i1 < len1 || i2 >= len2) {
arr[i++] = arr1[i1++];
}
if (i2 < len2 || i1 >= len1) {
arr[i++] = arr2[i2++];
}
}
cout<<"Merged array: ";
for (int i=0; i<len; i++) {
cout<<arr[i]<<", ";
}
cout<<" ";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.