Open In App

C Program To Merge Two Arrays

Last Updated : 29 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

To merge 2 arrays in C language we will use the following approaches:

  1. Using Quaint Methodology 
  2. Using Functions

Input:

arr1 = [1, 2, 3, 4, 5] 
arr2 = [6, 7, 8, 9, 10] 

Output: 

arr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

1. Using Quaint Methodology

C




// C Program To Merge Two Arrays
// using Quaint Methodology
#include <stdio.h>
int main()
{
    int arr1size = 5, arr2size = 5, arr_resultsize, i, j;
 
    // elements of first Array
    int a[5] = { 1, 2, 3, 4, 5 };
 
    // elements of Second Array
    int b[5] = { 6, 7, 8, 9, 10 };
 
    // resultant Array Size Declaration
    arr_resultsize = arr1size + arr2size;
    int c[arr_resultsize];
 
    // copying array 1 elements into an array
    for (i = 0; i < arr1size; i++) {
        c[i] = a[i];
    }
 
    // copying array 2 elements into an array
    for (i = 0, j = arr1size;
         j < arr_resultsize && i < arr2size; i++, j++) {
        c[j] = b[i];
    }
 
    // Array Elements After Merging
    for (i = 0; i < arr_resultsize; i++) {
        printf("%d ", c[i]);
    }
    return 0;
}


Output

1 2 3 4 5 6 7 8 9 10 

2. Using Functions 

C




// C Program To Merge Two Arrays
// using functions
#include <stdio.h>
 
int mergearray(int a[], int b[], int arr1size, int arr2size)
{
 
    // resultant Array Size Declaration
    int arr_resultsize = arr1size + arr2size;
    int c[arr_resultsize], i, j;
 
    // copying array 1 elements in to c array
    for (i = 0; i < arr1size; i++) {
        c[i] = a[i];
    }
 
    // copying array 2 elements in to c array
    for (i = 0, j = arr1size;
         j < arr_resultsize && i < arr2size; i++, j++) {
        c[j] = b[i];
    }
 
    // Array Elements After Merging
    for ( int k = 0; k < arr_resultsize; k++) {
        printf("%d ", c[k]);
    }
}
 
int main()
{
    int arr1size = 5, arr2size = 5;
 
    // elements of first Array
    int a[5] = { 1, 2, 3, 4, 5 };
 
    // elements of Second Array
    int b[5] = { 6, 7, 8, 9, 10 };
 
    printf("%d", mergearray(a, b, arr1size, arr2size));
    return 0;
}


Output

1 2 3 4 5 6 7 8 9 10 0

Time complexity: O(M+N) where M and N are size of given arrays a and b respectively
Auxiliary space: O(M+N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads