- 3

How to create alternative array using pointers? (Solved)

Let A and B be two arrays. Write a function to create a new array C that contains elements alternately from A and B beginning with the first element of A. Use pointer to access the elements from the array C. If you run out of elements in one of the lists (arrays), then append the remaining elements of the other list (array) to C. Input: A [] = [1,2,3], B [] = [5,6] Output: C [] = [1,5,2,6,3]

25th Jun 2021, 2:29 AM
Karthik
8 Respostas
+ 1
#include<iostream> using namespace std; void AltrMerge(int ar1[],int ar2[],int ar3[],int n1,int n2) { int i=0,j=0,k=0; while (i<n1 && j<n2) { ar3[k++] = ar1[i++]; ar3[k++] = ar2[j++]; } while (i<n1) { ar3[k++] = ar1[i++]; } while (j<n2) { ar3[k++] = ar2[j++]; } } int main() { int i,n1,n2,ar1[n1],ar2[n2],ar3[n1+n2],*ptr1,*ptr2,*ptr3; cout <<" Input the number of elements in 1st array : "; cin >>n1; cout <<" Input "<<n1<<" number of elements in 1st array : \n"; for(i=0;i<n1;i++) { cout <<" element - "<<i+1<<" : "; cin >>ar1[i]; } ptr1=ar1; cout <<" Input the number of elements in 2nd array : "; cin >>n2; cout <<" Input "<<n2<<" number of elements in 1st array : \n"; for(i=0;i<n2;i++) { cout <<" element - "<<i+1<<" : "; cin >>ar2[i]; } ptr2=ar2; AltrMerge(ar1,ar2,ar3,n1,n2); ptr3=ar3; cout << "Array after merging\n"; for (i=0;i<n1+n2;i++) { cout <<*ptr3<<" "; ptr3++; } return 0; }
25th Jun 2021, 5:21 PM
Karthik
+ 1
Martin Taylor Thank you
26th Jun 2021, 4:38 AM
Karthik