Write a C program to find the intersection of two arrays.
#include <stdio.h>
#define MAX 256
int main() {
int arr1[MAX], arr2[MAX], output[MAX];
int i, j, k = 0, flag, num1, num2;
/* get the number of entries for the first array */
printf("Enter the number entries in first array:");
scanf("%d", &num1);
/* get the number of entries for second array from the user */
printf("Enter the number of entries in second array:");
scanf("%d", &num2);
/* get the entries for first array from the user */
printf("Enter your entries for first array:\n");
for (i = 0; i < num1; i++) {
printf("Data[%d]: ", i);
scanf("%d", &arr1[i]);
}
/* get the entries for the second array from the user */
printf("Enter your entries for second array:\n");
for (i = 0; i < num2; i++) {
printf("Data[%d]: ", i);
scanf("%d", &arr2[i]);
}
#define MAX 256
int main() {
int arr1[MAX], arr2[MAX], output[MAX];
int i, j, k = 0, flag, num1, num2;
/* get the number of entries for the first array */
printf("Enter the number entries in first array:");
scanf("%d", &num1);
/* get the number of entries for second array from the user */
printf("Enter the number of entries in second array:");
scanf("%d", &num2);
/* get the entries for first array from the user */
printf("Enter your entries for first array:\n");
for (i = 0; i < num1; i++) {
printf("Data[%d]: ", i);
scanf("%d", &arr1[i]);
}
/* get the entries for the second array from the user */
printf("Enter your entries for second array:\n");
for (i = 0; i < num2; i++) {
printf("Data[%d]: ", i);
scanf("%d", &arr2[i]);
}
/* finds the intersection of two given arrays */
for (i = 0; i < num1; i++) {
flag = 0;
/* find the intersecting elements */
for (j = 0; j < num2; j++) {
if (arr1[i] == arr2[j]) {
flag = 1;
break;
}
}
if (flag) {
/* dont allow duplicates */
for (j = 0; j < k; j++) {
if (arr1[i] == output[j]) {
break;
}
}
if (j == k) {
output[k++] = arr1[i];
}
}
}
/* print the results */
printf("\nIntersection of given two arrays:\n");
for (i = 0; i < k; i++) {
printf("%d ", output[i]);
}
printf("\n");
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the number entries in first array:5
Enter the number of entries in second array:5
Enter your entries for first array:
Data[0]: 10
Data[1]: 20
Data[2]: 10
Data[3]: 30
Data[4]: 20
Enter your entries for second array:
Data[0]: 10
Data[1]: 50
Data[2]: 60
Data[3]: 20
Data[4]: 20
Intersection of given two arrays:
10 20
Enter the number entries in first array:5
Enter the number of entries in second array:5
Enter your entries for first array:
Data[0]: 10
Data[1]: 20
Data[2]: 10
Data[3]: 30
Data[4]: 20
Enter your entries for second array:
Data[0]: 10
Data[1]: 50
Data[2]: 60
Data[3]: 20
Data[4]: 20
Intersection of given two arrays:
10 20
No comments:
Post a Comment