C语言求两个数组的交集
时间: 2023-05-29 12:01:20 浏览: 224
N个集合求交集C语言代码
5星 · 资源好评率100%
以下是两个数组的交集的C语言代码:
```c
#include <stdio.h>
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {3, 5, 7, 9};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
int intersection[size1]; // 交集数组
int count = 0; // 交集数量
// 遍历arr1
for (int i = 0; i < size1; i++) {
int found = 0; // 是否已找到该元素
// 遍历arr2,寻找相等的元素
for (int j = 0; j < size2; j++) {
if (arr1[i] == arr2[j]) {
found = 1;
break;
}
}
if (found) {
intersection[count++] = arr1[i]; // 将该元素添加到交集数组中
}
}
// 输出交集
printf("Intersection: ");
for (int i = 0; i < count; i++) {
printf("%d ", intersection[i]);
}
printf("\n");
return 0;
}
```
输出:
```
Intersection: 3 5
```
阅读全文