Program to merge two arrays in C

We will merge two arrays into another array by C program in this guide. We consider that these two arrays are sorted. If not sorted we can sort them using any sorting algorithm.

At first we will take two array and their element as input from the user. Then we merge these two arrays to get a large array. We consider that they are in ascending order. If not we have to sort them. We can sort them before using merge function as well as we can merge them then sort the large array. However, sorting them after merging takes more time.

After merging we will get a larger sorted array. Let’s get started with C program.

C program to merge two arrays

// merge two arrays using c programming language
// Here you should enter array element in ascending order

#include <stdio.h>

// function to merge two array
void merge_two_arrays(int arr1[], int size1, int arr2[], int size2, int arr3[]){
  int a, b, c;
  a = b = 0;

  for(a = 0; a < size1 + size2;){

    if(b < size1 && c < size2){

      if(arr1[b] < arr2[c]){
        arr3[a] = arr1[b];
        b++;

      }else{
        arr3[a] = arr2[c];
        c++;
      }
      a++;

    }else if(b == size1){

      for(; a < size1 + size2;){
        arr3[a] = arr2[c];
        c++;
        a++;
      }

    }else{
      for(; a < size1 + size2;) {
        arr3[a] = arr1[b];
        b++;
        a++;
      }
    }
  }
}
// merge function close here

// main function start
int main(){
  int first_array[50], second_array[50], sorted_array[100], num1, num2, j;

  printf("Enter how many element in first array here : ");
  scanf("%d", &num1);

  printf("Enter all element of first array here : \n");
  for(j = 0; j < num1; j++){
    scanf("%d", &first_array[j]);
  }

  printf("\nEnter how many element in second array here : ");
  scanf("%d", &num2);

  printf("Enter all elements of second array here : \n");
  for(j = 0; j < num2; j++){
    scanf("%d", &second_array[j]);
  }

  merge_two_arrays(first_array, num1, second_array, num2, sorted_array);

  printf("\nArray after merging and sorting is : \n");

  for(j = 0; j < num1 + num2; j++){
    printf("%d ", sorted_array[j]);
  }

  return 0;
}

Output of merge two array program:

merge-two-array-in-c-c-program-to-merge-two-array