Q:

C program to find the intersection of two arrays

0

C program to find the intersection of two arrays

All Answers

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

Here, we will create two integer arrays and find the intersection of both arrays and print the result on the console screen.

Program:

The source code to find the intersection 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 Intersection of two arrays

#include <stdio.h>

int intersection(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]) {
            i++;
        }
        else if (arr1[i] > arr2[j]) {
            j++;
        }
        else {
            arr3[k] = arr1[i];
            i++;
            j++;
            k++;
        }
    }

    return k;
}

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

    int len = 0;
    int cnt = 0;

    len = intersection(arr1, arr2, arr3);

    printf("Intersection is: ");
    for (cnt = 0; cnt < len; cnt++)
        printf("%d ", arr3[cnt]);

    printf("\n");

    return 0;
}

Output:

Intersection is: 2 3 5

Explanation:

Here, we created two arrays arr1arr2 with 5 integer elements. Then we find the intersection of both arrays using the intersection() function and assign the result into the arr3 array.  The intersection() 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 union of two arrays... >>
<< C program to find the median of two arrays using a...