C program to merge two array to third array

Category: C Program

Learn how to write a C program to merge two arrays into a third array. This article provides a detailed explanation and sample code for merging arrays using a simple iterative approach.

Merging two arrays into a third array is a common task in C programming, which can be useful in various applications such as combining datasets, managing lists, and processing sequences. This article will guide you through writing a C program to merge two arrays into a third array, providing a detailed explanation and sample code.

Steps to Merge Two Arrays

To merge two arrays into a third array, we can follow these steps:

  1. Input the Arrays: Read the elements of the two arrays from the user.
  2. Merge the Arrays: Combine the elements of the two arrays into a third array.
  3. Print the Result: Output the merged array to the console.

We'll use a simple iterative approach to achieve this.

Write a C program to merge two array to third array

#include <stdio.h>

int main() {
    int size1, size2;

    // Input size and elements of the first array
    printf("Enter the size of the first array: ");
    scanf("%d", &size1);
    int arr1[size1];
    printf("Enter %d elements for the first array -\n", size1);
    for (int i = 0; i < size1; i++) {
        scanf("%d", &arr1[i]);
    }

    // Input size and elements of the second array
    printf("Enter the size of the second array: ");
    scanf("%d", &size2);
    int arr2[size2];
    printf("Enter %d elements for the second array -\n", size2);
    for (int i = 0; i < size2; i++) {
        scanf("%d", &arr2[i]);
    }

    // Declare the third array with size equal to the sum of the first and second arrays
    int size3 = size1 + size2;
    int arr3[size3];

    // Copy elements of the first array to the third array
    for (int i = 0; i < size1; i++) {
        arr3[i] = arr1[i];
    }

    // Copy elements of the second array to the third array
    for (int i = 0; i < size2; i++) {
        arr3[size1 + i] = arr2[i];
    }

    // Print the merged array
    printf("Merged array: ");
    for (int i = 0; i < size3; i++) {
        printf("%d ", arr3[i]);
    }

    return 0;
}

Output

Enter the size of the first array: 5
Enter 5 elements for the first array -
1
2
3
4
5
Enter the size of the second array: 4
Enter 4 elements for the second array -
11
22
33
44
Merged array: 1 2 3 4 5 11 22 33 44

Explanation

  1. Input the Arrays: The user inputs the size and elements of the two arrays, arr1 and arr2.
  2. Merge the Arrays:
    • A third array, arr3, is declared with a size equal to the sum of the sizes of the first and second arrays.
    • The elements of the first array are copied to the beginning of the third array.
    • The elements of the second array are copied to the subsequent positions in the third array.
  3. Print the Result: The merged array is printed to the console.

Recommended Posts