C Program to merge two arrays

#include <stdio.h>
#include <stdlib.h>

int main() {
    int size1, size2, newSize, i, j;
    int *arr1, *arr2, *newArr;

    printf("=== C Program to Merge Two Arrays ===\n\n");

    // Input size of first array
    printf("Enter the number of elements in the First Array: ");
    scanf("%d", &size1);
    if (size1 <= 0) {
        printf("Array size must be positive.\n");
        return 1;
    }

    // Dynamically allocate memory for first array
    arr1 = (int *)malloc(size1 * sizeof(int));
    if (arr1 == NULL) {
        printf("Memory allocation failed for First Array.\n");
        return 1;
    }

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

    // Input size of second array
    printf("\nEnter the number of elements in the Second Array: ");
    scanf("%d", &size2);
    if (size2 <= 0) {
        printf("Array size must be positive.\n");
        free(arr1);
        return 1;
    }

    // Dynamically allocate memory for second array
    arr2 = (int *)malloc(size2 * sizeof(int));
    if (arr2 == NULL) {
        printf("Memory allocation failed for Second Array.\n");
        free(arr1);
        return 1;
    }

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

    // Merge both arrays
    newSize = size1 + size2;
    newArr = (int *)malloc(newSize * sizeof(int));
    if (newArr == NULL) {
        printf("Memory allocation failed for Merged Array.\n");
        free(arr1);
        free(arr2);
        return 1;
    }

    for (i = 0; i < size1; i++) {
        newArr[i] = arr1[i];
    }
    for (j = 0; j < size2; j++) {
        newArr[i++] = arr2[j];
    }

    // Display merged array
    printf("\nMerged Array Elements:\n");
    for (i = 0; i < newSize; i++) {
        printf("%d ", newArr[i]);
    }
    printf("\n");

    // Free dynamically allocated memory
    free(arr1);
    free(arr2);
    free(newArr);

    return 0;
}

Output

=== C Program to Merge Two Arrays ===

Enter the number of elements in the First Array: 5
Enter the elements of the First Array:
Element [0]: 3
Element [1]: 2
Element [2]: 4
Element [3]: 1
Element [4]: 2

Enter the number of elements in the Second Array: 6
Enter the elements of the Second Array:
Element [0]: 23
Element [1]: 2
Element [2]: 11
Element [3]: 23
Element [4]: 2
Element [5]: 12

Merged Array Elements:
3 2 4 1 2 23 2 11 23 2 12 
What did you think?

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now