C

How To Merge Two Arrays in C

In this tutorial, we are going to see how to merge two arrays into a third array in C. The arrays are supposed to be sorted in ascending order. You enter two sorted arrays and merge them into a larger array. If the arrays are not sorted, you can sort them first and then use the merge function.

See also : Merge Sort in C
See also : Quick Sort in C
See also : Bubble Sort in C

 

 

How To Merge Two Arrays in C
#include <stdio.h>
 
int main()
{
  int arr1[50], arr2[50], arr3[100];
  int nbr1, nbr2, nbr3, i, j;
    
  printf("Enter the number of elements in the 1st array: ");
  scanf("%d", &nbr1);
  printf("Enter the array elements: ");
  for(i = 0; i < nbr1; i++)
  {
    scanf("%d", &arr1[i]);
  }
    
  printf("Enter the number of elements in the 2nd array: ");
  scanf("%d", &nbr2);
  printf("Enter the array elements: ");
  for(i = 0; i < nbr2; i++)
  {
    scanf("%d", &arr2[i]);
  }
    
  for(i = 0; i < nbr1; i++)
  {
    arr3[i] = arr1[i];
  }
    
  nbr3 = nbr1 + nbr2;
   
  for(i = 0, j = nbr1; j < nbr3 && i < nbr2; i++, j++)
  {
    arr3[j] = arr2[i];
  }
   
  printf("The merged array is: ");
  for(i = 0; i < nbr3; i++)
  {
    printf("%4d",arr3[i]);
  }
   
  return 0;
}

Output:

Enter the number of elements in the 1st array: 3
Enter the array elements: 1 2 3
Enter the number of elements in the 2nd array: 3
Enter the array elements: 4 5 6
The merged array is:    1   2   3   4   5   6

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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