C Program To Merge Two Arrays

In this tutorial, i am going to show you how to merge two arrays with the help of standard method and function in c programs.

All C Programs To Merge Two Arrays

  • C Program To Merge Two Arrays using Standard Method
  • C Program To Merge Two Arrays using Function

C Program To Merge Two Arrays using Standard Method

#include <stdio.h>
print(int *a,int n)
 { 
    int i;
    
	
 
    for(i=0; i<n; i++)
    {
      
        	printf("%d  ",a[i]);
 
		 
    }
 	
 }
  
 
int main()
{
    int a[10000],b[10000],c[20000],i,n1,n2 ;
   
    printf("Enter size of the 1st array : ");
    scanf("%d", &n1);
    printf("Enter elements in array : ");
    for(i=0; i<n1; i++)
    {
        scanf("%d",&a[i]);
    }
    printf("Enter size of the 2nd array : ");
    scanf("%d",&n2);
 
    printf("Enter elements in array : ");
    for(i=0; i<n2; i++)
    {
        scanf("%d",&b[i]);
    }
    
    for(i=0; i<n1+n2; i++)
    {
       if(i<n1)
          c[i]=a[i];
          else
            c[i]=b[i-n1];
 
    }
     
    printf(" 1st array :\n");
 
    print(a,n1);
                     
	printf("\n2nd array :\n");
 
    print(b,n2);
            
	printf("\nMerged array :\n");
 
    print(c,n1+n2);
  
    return 0;
}

The result of the above c program; as follows:

Enter size of the 1st array : 5
Enter elements in array : 1 2 3 4 5
Enter size of the 2nd array : 3
Enter elements in array : 6 7 8
1st array :
1  2  3  4  5  
2nd array :
6  7  8  
Merged array :
1  2  3  4  5  6  7  8  

C Program To Merge Two Arrays using Function

#include <stdio.h>
 
merge(int *a,int *b,int *c,int n1,int n2)
{ int i;  
	      
    for(i=0; i<n1+n2; i++)
    {
         if(i<n1)
          c[i]=a[i];
          else
            c[i]=b[i-n1];
	}
         
   
          
     
     
 }
 
print(int *a,int n)
 { 
    int i;
    
	
 
    for(i=0; i<n; i++)
    {
      
        	printf("%d  ",a[i]);
 
		 
    }
 	
 }
  
int main()
{
    int a[10000],b[10000],c[20000],i,n1,n2,n ;
   
    printf("Enter size of the 1st array : ");
    scanf("%d", &n1);
    printf("Enter elements in array : ");
    for(i=0; i<n1; i++)
    {
        scanf("%d",&a[i]);
    }
    printf("Enter size of the 2nd array : ");
    scanf("%d",&n2);
 
    printf("Enter elements in array : ");
    for(i=0; i<n2; i++)
    {
        scanf("%d",&b[i]);
    }
    
    merge(a,b,c,n1,n2);
     
    printf(" 1st array :\n");
 
    print(a,n1);
                     
	printf("\n2nd array :\n");
 
    print(b,n2);
            
	printf("\n3rd array :\n");
 
    print(c,n1+n2);
} 

The result of the above c program; as follows:

Enter size of the 1st array : 5
Enter elements in array : 1 2 3 4 5
Enter size of the 2nd array : 3
Enter elements in array : 6 7 8
1st array :
1  2  3  4  5  
2nd array :
6  7  8  
Merged array :
1  2  3  4  5  6  7  8  

More C Programming Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.