-- --

C program to merge two sorted arrays

Program in the C programming language to merge two sorted arrays. Note that after this code is compiled, the elements of the arrays should be entered  in the ascending order as the program is made according to it. Below is the code of the C program –

/* C Program to Merge Two Sorted Arrays */

#include <stdio.h>
void main()
{
     int a[50], b[50], c[100], m, n, i, j, k=0;
     printf("\nEnter size of array A: ");
     scanf("%d", &m);
     printf("\nEnter sorted elements of array A:\n");
     for(i=0; i<m; i++)
     {
              scanf("%d", &a[i]);
     }
     
     printf("\nEnter size of array B: ");
     scanf("%d", &n);
     printf("\nEnter sorted elements of array B:\n");
     for(i=0; i<n; i++)
     {
              scanf("%d", &b[i]);
     }
     
     i=0;
     j=0;
     while(i<m && j<n)
     {
               if(a[i] < b[j])
               {
                       c[k] = a[i];
                       i++;
               }
               else
               {
                   c[k] = b[j];
                   j++;
               }
               k++;
     }
     
     if(i >= m)
     {
          while(j<n)
          {
                    c[k] = b[j];  
                    j++;
                    k++;
          }
     }
     
     if(j >= n)
     {
          while(i<m)
          {
                    c[k] = a[i];
                    i++;
                    k++;
          }
     }
     
     printf("\nAfter merging:\n");
     for(i=0; i<m+n; i++)
     {
              printf("\n%d", c[i]);
     }
     getch();
}

Input-
Enter size of array A: 5
Enter sorted elements of array A:
2    6    15    23    35

Enter size of array B: 4
Enter sorted elements of array B:
7    13    14    39

Output-
After merging the elements are:
2    6    7    13    14    15    23    35    39

yashan has written 69 articles

2 thoughts on “C program to merge two sorted arrays

  1. Norbert G Baranyikwa says:

    in the insertion point you have limit the user by entering numbers in ascending order, can it be otherwise?

    -algorithm of that:
    -enter elements of an array A
    -sort elements of an array A
    -enter elements of an array B
    -sort elements of an array B

    -merge array A and array B
    -display the output

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>