Merge Two Arrays in C
To merge two arrays in C, we create a new array with a size equal to the sum of both arrays and copy elements from both arrays into it. We use loops to iterate through the source arrays and store elements sequentially in the merged array.
Examples of Merging Two Arrays
1. Merging Two Arrays into a Third Array Using a for Loop
In this example, we declare two integer arrays and merge them into a third array using a for loop.
main.c
</>
Copy
#include <stdio.h>
int main() {
int arr1[] = {1, 2, 3};
int arr2[] = {4, 5, 6};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
int merged[size1 + size2];
// Copy elements of arr1 into merged
for (int i = 0; i < size1; i++) {
merged[i] = arr1[i];
}
// Copy elements of arr2 into merged
for (int i = 0; i < size2; i++) {
merged[size1 + i] = arr2[i];
}
// Print merged array
printf("Merged Array: ");
for (int i = 0; i < size1 + size2; i++) {
printf("%d ", merged[i]);
}
return 0;
}
Explanation:
- We declare two integer arrays,
arr1andarr2, and determine their sizes usingsizeof(). - A third array,
merged, is created with a size equal to the sum ofsize1andsize2. - We use a
forloop to copy all elements fromarr1intomerged. - Another
forloop copies elements fromarr2into the next available positions ofmerged. - Finally, a loop iterates through
mergedto print all elements in sequence.
Output:
Merged Array: 1 2 3 4 5 6
2. Merging Two Arrays Using a Function
In this example, we define a function to merge two arrays, making our program more reusable and structured.
main.c
</>
Copy
#include <stdio.h>
void mergeArrays(int arr1[], int size1, int arr2[], int size2, int merged[]) {
for (int i = 0; i < size1; i++) {
merged[i] = arr1[i];
}
for (int i = 0; i < size2; i++) {
merged[size1 + i] = arr2[i];
}
}
int main() {
int arr1[] = {10, 20, 30};
int arr2[] = {40, 50, 60};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
int merged[size1 + size2];
// Call function to merge arrays
mergeArrays(arr1, size1, arr2, size2, merged);
// Print merged array
printf("Merged Array: ");
for (int i = 0; i < size1 + size2; i++) {
printf("%d ", merged[i]);
}
return 0;
}
Explanation:
- We define a function
mergeArrays()that takes two arrays, their sizes, and an output array as arguments. - Inside the function, two
forloops copy elements fromarr1andarr2intomerged. - In
main(), we declare two integer arrays and determine their sizes. - We call
mergeArrays()to merge the two arrays intomerged. - A loop iterates through
mergedto print the merged elements.
Output:
Merged Array: 10 20 30 40 50 60
Conclusion
In this tutorial, we explored how to merge two arrays in C with different approaches:
- Using a
forLoop: A simple approach to copy elements sequentially. - Using a Function: A structured and reusable way to merge arrays.
