Q:

C program to find the union of two arrays

0

C program to find the union of two arrays

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Given two integer arrays, we have to find the union using C program.

Program:

The source code to find the union of two arrays is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to find the union of two arrays

#include <stdio.h>

int findUnion(int arr1[], int arr2[], int arr3[])
{
    int i = 0;
    int j = 0;
    int k = 0;

    while ((i < 5) && (j < 5)) {
        if (arr1[i] < arr2[j]) {
            arr3[k] = arr1[i];
            i++;
            k++;
        }
        else if (arr1[i] > arr2[j]) {
            arr3[k] = arr2[j];

            j++;
            k++;
        }
        else {
            arr3[k] = arr1[i];
            i++;
            j++;
            k++;
        }
    }

    if (i == 5) {
        while (j < 5) {
            arr3[k] = arr2[j];
            j++;
            k++;
        }
    }
    else {
        while (i < 5) {
            arr3[k] = arr1[i];
            i++;
            k++;
        }
    }
    return k;
}

int main()
{
    int arr1[5] = { 1, 2, 3, 4, 5 };
    int arr2[5] = { 2, 3, 5, 7, 8 };
    int arr3[10] = { 0 };

    int len = 0;
    int cnt = 0;

    len = findUnion(arr1, arr2, arr3);

    printf("Union of arr1 and arr2 is: ");
    for (cnt = 0; cnt < len; cnt++)
        printf("%d ", arr3[cnt]);

    printf("\n");

    return 0;
}

Output:

Union of arr1 and arr2 is: 1 2 3 4 5 7 8

Explanation:

Here, we created two arrays arr1arr2 with 5 integer elements. Then we find the union of both arrays using the findUnion() function and assign the result into the arr3 array. The findUnion() function is a user-defined function. After that, we printed the intersected elements on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

One Dimensional Array Programs / Examples in C programming language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to find the size of the array using macr... >>
<< C program to find the intersection of two arrays...