lecture 3 code

PHOTO EMBED

Mon Aug 26 2024 06:55:05 GMT+0000 (Coordinated Universal Time)

Saved by @mdimtiyazalam

#include <stdio.h>

int main() {
    int n, m, i, j, k;

    // Read the size of the first array
    scanf("%d", &n);

    // Read the elements of the first array
    int arr1[n];
    for (i = 0; i < n; i++) {
        scanf("%d", &arr1[i]);
    }

    // Read the size of the second array
    scanf("%d", &m);

    // Read the elements of the second array
    int arr2[m];
    for (i = 0; i < m; i++) {
        scanf("%d", &arr2[i]);
    }

    // Merge the arrays into a single sorted array without duplicates
    int merged[n + m];
    i = 0;
    j = 0;
    k = 0;
    while (i < n && j < m) {
        if (arr1[i] < arr2[j]) {
            merged[k++] = arr1[i++];
        } else if (arr1[i] > arr2[j]) {
            merged[k++] = arr2[j++];
        } else {
            merged[k++] = arr1[i++];
            j++;
        }
    }

    // Add remaining elements from the first array
    while (i < n) {
        merged[k++] = arr1[i++];
    }

    // Add remaining elements from the second array
    while (j < m) {
        merged[k++] = arr2[j++];
    }

    // Print the merged array
    for (i = 0; i < n; i++) {
        printf("%d ", merged[i]);
    }
    printf("\n");
    for (i = n; i < n + m; i++) {
        printf("%d ", merged[i]);
    }
    printf("\n");

    return 0;
}
content_copyCOPY