×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to find the union of two arrays

Here, we are going to learn how to find the union of two arrays in C programming language?
Submitted by Nidhi, on July 12, 2021

Problem statement

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

Finding union of two arrays

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

// 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 arr1, arr2 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.

C One-Dimensional Array Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.