May 11, 2012

C program to merge two arrays.

Arrays in C.
Write a C program to merge two arrays.
In this program we check the elements of arrays A, B and put that elements in the resulted array C in sorted manner.
Read more about C Programming Language . and read the C Programming Language (2nd Edition). by K and R.

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

#include<stdio.h>
#include<conio.h>
void main( )
{
    int n,m,i,j,k,c[40],a[20],b[20];
    clrscr ();
    printf("Enter how many elements for array A?:\n");
    scanf("%d",&n);
    printf  ("Enter how many elements for array B?:\n");
   scanf("%d",&m);
    printf("Enter elements for A:-\n");
    for(i=0;i<n;i++)
    scanf("%d",&a[i]);
    printf("Enter elements for B:-\n");
    for(j=0;j<m;j++)
    scanf("%d",&b[j]);
    i=j=k=0;
    while(i<n&&j<m)
    {
        if(a[i]<b[j])
        c[k++]=a[i++];
        else
        if(a[i]>b[j])
        c[k++]=b[j++];
        else
        
        {
            c[k++]=b[j++];
            i++;
            j++;
        }
    }
    
    if(i<n)
    {
        int t;
        for(t=0;t<n;t++)
        
        c[k++]=a[i++];
    }
    if(j<m)
    {
        int t;
        for(t=0;t<m;t++)
        {
            c[k++]=b[j++];
        }
    }
    printf("\n\n Merged Array C:\n\n")
    for(k=0;k<(m+n);k++)
    printf("\t \n %d ",c[k]);
    getch();
}
Read more Similar C Programs
Data Structures

Learn C Programming
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link