Someone asked me how to merge two arrays into one array by using the C programming language so that here we are sharing a C program which will merge the two arrays into one array and print the output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | #include<stdio.h> int main() { int arr1[30], arr2[30], res[60]; int i, j, k, n1, n2; printf("\nEnter no of elements in 1st array :"); scanf("%d", &n1); for (i = 0; i < n1; i++) { scanf("%d", &arr1[i]); } printf("\nEnter no of elements in 2nd array :"); scanf("%d", &n2); for (i = 0; i < n2; i++) { scanf("%d", &arr2[i]); } i = 0; j = 0; k = 0; // Merging starts while (i < n1 && j < n2) { if (arr1[i] <= arr2[j]) { res[k] = arr1[i]; i++; k++; } else { res[k] = arr2[j]; k++; j++; } } /* Some elements in array 'arr1' are still remaining where as the array 'arr2' is exhausted */ while (i < n1) { res[k] = arr1[i]; i++; k++; } /* Some elements in array 'arr2' are still remaining where as the array 'arr1' is exhausted */ while (j < n2) { res[k] = arr2[j]; k++; j++; } //Displaying elements of array 'res' printf("\nMerged array is :"); for (i = 0; i < n1 + n2; i++) printf("%d ", res[i]); return (0); } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: c program examples, c program examples with output, c program to merge two arrays, c tutorials, how to merge two arrays in c, merge two arrays, merge two arrays in c