Home > Backend Development > C++ > body text

How to merge two arrays in C language?

WBOY
Release: 2023-09-10 09:05:02
forward
1543 people have browsed it

How to merge two arrays in C language?

Taking two arrays as input, try to merge or concatenate the two arrays and store the result in the third array.

The logic of merging two arrays is as shown below- p>

J=0,k=0
for(i=0;i<o;i++) {// merging two arrays
   if(a[j]<=b[k]){
      c[i]=a[j];
      j++;
   } else {
      c[i]=b[k];
      k++;
   }
}
Copy after login

Program

The program given below shows how to merge two arrays in C programming language-

#include<stdio.h>
#include<stdlib.h>
int main(){
   int a[10],b[10],c[20],m,n,o,i,j,k,temp;
   printf("Enter size of Array1</p><p>");
   scanf("%d",&n);
   printf("Enter size of Array2</p><p>");
   scanf("%d",&m);
   o=m+n; //size of third array
   printf("Enter Elements of Array1</p><p>");
   for(i=0;i<n;i++){
      scanf("%d",&a[i]);
   }
   printf("Enter Elements of Array2</p><p>");
   for(i=0;i<m;i++){
      scanf("%d",&b[i]);
   }
   //sorting first array
   for(i=0;i<n;i++){
      for(j=0;j<n-1-i;j++){
         if(a[j]>a[j+1]){
            temp=a[j];
            a[j]=a[j+1];
            a[j+1]=temp;
         }
      }
   }
   //sorting second array
   for(i=0;i<m;i++){
      for(j=0;j<m-1-i;j++){
         if(b[j]>b[j+1]){
            temp=b[j];
            b[j]=b[j+1];
            b[j+1]=temp;
         }
      }
   }
   printf("Elements of Array1</p><p>");
   for(i=0;i<n;i++){
      printf("a[%d]=%d</p><p>",i,a[i]);
   }
   printf("Elements of Array2</p><p>");
   for(i=0;i<m;i++){
      printf("b[%d]=%d</p><p>",i,b[i]);
   }
   j=0;
   k=0;
   for(i=0;i<o;i++){ // merging two arrays
      if(a[j]<=b[k]){
         c[i]=a[j];
         j++;
      }
      else{
         c[i]=b[k];
         k++;
      }
   }
   printf("Merged array is :</p><p>");
   for(i=0;i<o;i++){
      printf("c[%d]=%d</p><p>",i,c[i]);
   }
}
Copy after login

Output

When the above program is executed, it produces the following results −

Enter Elements of Array1
1
2
3
4
Enter Elements of Array2
6
8
3
Elements of Array1
a[0]=1
a[1]=2
a[2]=3
a[3]=4
Elements of Array2
b[0]=3
b[1]=6
b[2]=8
Merged array is:
c[0]=1
c[1]=2
c[2]=3
c[3]=3
c[4]=4
c[5]=6
c[6]=8
Copy after login

The above is the detailed content of How to merge two arrays in C language?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template