dhairyashah
Portfolio

Sep 26th, 2023

How to merge two arrays in C?

Author Picture

Dhairya Shah

Software Engineer

Merging two arrays in C is a common operation when working with arrays and data structures. It involves combining the elements of two separate arrays into a single array, often to perform operations like sorting, searching, or simply creating a larger array. In this article, we will explore different methods to merge two arrays in C.

To merge two arrays, we will use the Third Array Method.

One of the simplest ways to merge two arrays in C is to create a third array and copy the elements from both arrays into it. Here’s an example:

#include<stdio.h>
int main(){
    int arr1[5] = {1,2,3,4,5};
    int arr2[5] = {6, 7, 8, 9, 10};
    
    int arrOneSize = sizeof(arr1) / sizeof(arr1[0]);
    int arrTwoSize = sizeof(arr2) / sizeof(arr2[0]);
    int totalSize = arrOneSize + arrTwoSize;
    
    int merged_arr[totalSize];
    
    for(int i = 0; i < arrOneSize; i++){
        merged_arr[i] = arr1[i];
    }
    
    for(int i = 0; i < arrTwoSize; i++){
        merged_arr[arrOneSize + i] = arr2[i];
    }
    
    for (int i = 0; i < totalSize; i++) {
        printf("%d ", merged_arr[i]);
    }
    
    return 0;
} 

In this code, we create a third array, ‘merged_arr,’ with enough space to hold both ‘arr1’ and ‘arr2.’ We then copy the elements of ‘arr1’ and ‘arr1’ into ‘merged_arr,’ resulting in a merged array.

Conclusion

In conclusion, merging two arrays in C can be accomplished using a straightforward approach by creating a third array to hold the combined elements of the original arrays. This method is simple to implement and easy to understand, making it suitable for various programming tasks where memory constraints are not a primary concern.

By following the example provided in the article, you can easily merge two arrays of integers. Remember that the size of the third array should be large enough to accommodate all the elements from both source arrays. Afterward, you can copy the elements from each source array into the merged array using loops.

I hope this article was helpful to you. Thanks for reading, have a great day!