查找两个数组相同元素C语言
时间: 2023-09-12 15:03:18 浏览: 168
两个数组相同元素的查找可以采用双重循环的方式,先将其中一个数组的元素遍历,再和另一个数组的元素一一比较。如果有相同的元素,则将其输出即可。下面是一个简单的C语言代码示例:
```c
#include <stdio.h>
int main()
{
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {4, 5, 6, 7, 8};
int len1 = sizeof(arr1) / sizeof(arr1[0]);
int len2 = sizeof(arr2) / sizeof(arr2[0]);
for (int i = 0; i < len1; i++)
{
for (int j = 0; j < len2; j++)
{
if (arr1[i] == arr2[j])
{
printf("%d ", arr1[i]);
}
}
}
return 0;
}
```
该程序输出结果为:4 5,即两个数组中相同的元素。
相关问题
用C语言实现求两个数组中相同元素
在C语言中,可以使用循环和临时存储来找出两个数组中相同的元素。这里是一个简单的示例,假设我们有两个整数数组`arr1[]`和`arr2[]`,以及它们的长度`n1`和`n2`:
```c
#include <stdio.h>
// 函数声明
void findCommon(int arr1[], int n1, int arr2[], int n2);
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int arr2[] = {4, 5, 6, 7, 8};
int n2 = sizeof(arr2) / sizeof(arr2[0]);
findCommon(arr1, n1, arr2, n2);
return 0;
}
// 查找并打印相同元素的函数
void findCommon(int arr1[], int n1, int arr2[], int n2) {
// 创建临时数组存放公共元素
int common[n1 + n2];
int j = 0; // 初始化计数器
for (int i = 0; i < n1 && j < n2; ++i) {
if (arr1[i] == arr2[j]) {
printf("%d ", arr1[i]); // 打印当前找到的公共元素
common[j++] = arr1[i]; // 把元素添加到common数组
}
}
// 如果还有剩余元素,说明arr2有未匹配的
while (j < n2) {
common[j++] = arr2[j - 1]; // 将arr2剩下的元素也放入common数组
}
printf("\nCommon elements are: ");
// 输出结果
for (int k = 0; k < j; ++k) {
printf("%d ", common[k]);
}
}
```
在这个例子中,`findCommon`函数会查找并打印出两个数组中相同的元素。如果需要的话,你可以稍作修改以适应其他类型的数组。
输入两个数组(数组元素个数6和8),输出在两个数组中都出现的元素用c语言编写
以下是一种可能的实现方式:
```
#include <stdio.h>
int main() {
int array1[6] = {1, 2, 3, 4, 5, 6};
int array2[8] = {2, 4, 6, 8, 10, 12, 14, 16};
int i, j;
printf("Common elements: ");
for (i = 0; i < 6; i++) {
for (j = 0; j < 8; j++) {
if (array1[i] == array2[j]) {
printf("%d ", array1[i]);
break;
}
}
}
printf("\n");
return 0;
}
```
这段代码定义了两个数组 `array1` 和 `array2`,然后使用两个嵌套的循环遍历这两个数组,找出在两个数组中都出现的元素并打印出来。具体来说,对于数组 `array1` 中的每一个元素,都在数组 `array2` 中查找是否存在相同的元素,如果存在则打印出来。为了避免重复输出相同的元素,内部循环使用 `break` 语句跳出循环。最终输出的就是两个数组中都出现的元素。
阅读全文
相关推荐
















