C++ Program to Merge Two Arrays

05/06/2024 0 By indiafreenotes

Merging two arrays in C++ can be achieved by creating a new array that is large enough to hold both arrays, and then copying the elements from the original arrays into the new array. Here’s an example program that demonstrates how to merge two arrays:

#include <iostream>

int main() {

    // Define the first array

    int arr1[] = {1, 3, 5, 7, 9};

    int size1 = sizeof(arr1) / sizeof(arr1[0]);

    // Define the second array

    int arr2[] = {2, 4, 6, 8, 10};

    int size2 = sizeof(arr2) / sizeof(arr2[0]);

    // Calculate the size of the merged array

    int mergedSize = size1 + size2;

    // Create a new array to hold the merged arrays

    int mergedArray[mergedSize];

    // Merge the two arrays

    // Copy elements from the first array

    for (int i = 0; i < size1; i++) {

        mergedArray[i] = arr1[i];

    }

    // Copy elements from the second array

    for (int i = 0; i < size2; i++) {

        mergedArray[size1 + i] = arr2[i];

    }

    // Output the merged array

    std::cout << “Merged array: “;

    for (int i = 0; i < mergedSize; i++) {

        std::cout << mergedArray[i] << ” “;

    }

    std::cout << std::endl;

    return 0;

}

Here’s how the program works:

  • The program starts by defining two arrays (arr1 and arr2) with some example values.
  • The sizes of the arrays are calculated using sizeof to determine the length of each array.
  • The program calculates the size of the merged array by summing the sizes of the two arrays.
  • A new array (mergedArray) is created to hold the combined elements of the original arrays.
  • The program uses a loop to copy elements from the first array to the merged array.
  • Another loop is used to copy elements from the second array to the merged array, starting from where the first array’s elements ended.
  • Finally, the program prints the merged array.