C语言求两个数组中相同的元素
时间: 2023-08-13 08:08:27 浏览: 281
可以使用双重循环遍历两个数组,将每个元素分别与另一个数组中的所有元素进行比较,找出相同的元素。具体实现可以参考下面的代码:
```c
#include <stdio.h>
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {3, 5, 7, 9, 11};
int len1 = sizeof(arr1) / sizeof(arr1[0]);
int len2 = sizeof(arr2) / sizeof(arr2[0]);
int i, j;
printf("相同的元素有:");
for (i = 0; i < len1; i++) {
for (j = 0; j < len2; j++) {
if (arr1[i] == arr2[j]) {
printf("%d ", arr1[i]);
}
}
}
printf("\n");
return 0;
}
```
以上代码输出结果为:相同的元素有:3 5
相关问题
c语言使两个数组的相同元素成为新的数组
可以通过双重循环来实现这个功能,具体步骤如下:
1. 定义两个数组arr1和arr2,并且定义一个新的数组result用于存储相同的元素。
2. 使用双重循环遍历arr1和arr2,判断两个数组中是否存在相同的元素。
3. 如果存在相同的元素,则将该元素存储到result数组中。
4. 最后输出result数组即可。
下面是示例代码:
```c
#include <stdio.h>
int main()
{
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {3, 4, 5, 6, 7};
int len1 = sizeof(arr1) / sizeof(int);
int len2 = sizeof(arr2) / sizeof(int);
int result[10];
int count = 0;
for (int i = 0; i < len1; i++) {
for (int j = 0; j < len2; j++) {
if (arr1[i] == arr2[j]) {
result[count++] = arr1[i];
}
}
}
printf("相同的元素为:");
for (int i = 0; i < count; i++) {
printf("%d ", result[i]);
}
printf("\n");
return 0;
}
```
在上面的示例代码中,我们定义了两个数组arr1和arr2,然后使用双重循环遍历这两个数组,如果发现有相同的元素,则将该元素存储到result数组中。最后输出result数组中的元素即可。
C语言 求两个数组中相同的元素,输入两个数组(数组元素个数6和8),输出在两个数组中都出现的元素
这个问题已经在上一个问题中回答过了,这里再给出一份代码供参考。
```c
#include <stdio.h>
int main() {
int a[6] = {2, 3, 4, 5, 6, 7};
int b[8] = {3, 5, 7, 9, 11, 13, 15, 19};
int i, j;
printf("两个数组中相同的元素有:");
for (i = 0; i < 6; i++) {
for (j = 0; j < 8; j++) {
if (a[i] == b[j]) {
printf("%d ", a[i]);
break;
}
}
}
return 0;
}
```
输出结果为:两个数组中相同的元素有:3 5 7
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)