The Program in C to merge two array a and b into third array is given below:
#include <stdio.h>
void merge_arrays(int a[], int size_a, int b[], int size_b, int c[]) {
int i = 0, j = 0, k = 0;
while (i < size_a && j < size_b) {
if (a[i] < b[j]) {
c[k++] = a[i++];
} else {
c[k++] = b[j++];
}
}
while (i < size_a) {
c[k++] = a[i++];
}
while (j < size_b) {
c[k++] = b[j++];
}
}
int main() {
int size_a, size_b;
printf("Enter the size of the first array: ");
scanf("%d", &size_a);
int a[size_a];
printf("Enter the elements of the first array: ");
for (int i = 0; i < size_a; i++) {
scanf("%d", &a[i]);
}
printf("Enter the size of the second array: ");
scanf("%d", &size_b);
int b[size_b];
printf("Enter the elements of the second array: ");
for (int i = 0; i < size_b; i++) {
scanf("%d", &b[i]);
}
int c[size_a + size_b];
merge_arrays(a, size_a, b, size_b, c);
printf("The merged array is: ");
for (int i = 0; i < size_a + size_b; i++) {
printf("%d ", c[i]);
}
return 0;
}
Output:
Enter the size of the first array: 3
Enter the elements of the first array: 12
14
19
Enter the size of the second array: 3
Enter the elements of the second array: 22
99
13
The merged array is: 12 14 19 22 99 13
Pro-Tips💡
This C program demonstrates a function called merge_arrays()
that takes in three arrays, a
, b
, and c
, and their respective sizes, size_a
, size_b
.
The function then merges the elements of the first two arrays (a
and b
) in sorted order into the third array (c
).
The main function prompts the user to enter the sizes and elements of two arrays (a
and b
), calls the merge_arrays()
function to merge the two arrays, and then prints the merged array.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.