C Program To Merge Two Arrays

C Program To Merge Two Arrays

#include<stdio.h>
void main(){
int ar1[10],ar2[10],ar3[10],i,j,n1,n2;

scanf("%d",&n1);
scanf("%d",&n2);

for(i=0;i<n1;i++){
    scanf("%d",&ar1[i]);
}

for(i=0;i<n2;i++){
    scanf("%d",&ar2[i]);
}

int n3=n1+n2;
for(i=0;i<n1;i++){
   ar3[i]=ar1[i]; 
}

for(i=0,j=n1;i<n2 && j<n3; i++,j++){
    ar3[j]=ar2[i];
}
printf("Printing merged array elements: ");

for(i=0;i<n3;i++){
    printf("%d\n",ar3[i]);
}}

Explanation – This program is first taking two arrays, and then adding them, In this program you can see that there are two for loops for two array. As you know that we are traversing from 0 index to last element, and taking input from the user using scanf function.

Now we are using another array to store first array using for loop, and then for the second array we are using another for loop and make sure that the second array element starts inserting after the first array elements.

Now using n3 = n1 + n2, we able to find total no. of index, and printing the value of final array.


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment