Home »
C programs »
C one-dimensional array programs
C program to find the intersection of two arrays
Here, we are going to learn how to find the intersection of two arrays in C programming language?
Submitted by Nidhi, on July 12, 2021
Problem Solution:
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 arr1, arr2 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.
C One-Dimensional Array Programs »