C Program to Find the Intersection of two Arrays: To find the union, add the first array’s elements to the set union. Now, add all the second array elements if they are not present in the set union.
C Program to Find the Intersection of two Arrays
#include <stdio.h>
int main(void) {
int arr1[100], arr2[100], len1, len2, i, p = 0, q = 0;
printf( "Enter lenght of first array (Max 100) \n");
scanf( " %d ", &len1);
printf( " Enter sorted values for first array \n");
for (i = 0; i < len1; i++) {
scanf(" %d ", &arr1[i]);
}
printf( "Enter length of second array (Max 100) \n");
scanf (" %d ", &len2);
printf (" Enter sorted values for second array \n");
for (i = 0; i < len2; i++) {
scanf( " %d ", &arr2[i]);
}
while (p <= len1 && q <= len2) {
if (arr1[p] < arr2[q]) {
p++;
} else if (arr2[q] < arr1[p]) {
q++;
} else if (arr1[p] == arr2[q]) {
printf (" %d ", arr1[p]);
p++;
q++;
}
}
return 0;
}
Output Of Program
Enter lenght of first array (Max 100)
5
4
Enter sorted values for first array
5
5
4
100
1000
Enter length of second array (Max 100)