c语言找到一个数组中出现次数最多的元素,并输出其出现次数
时间: 2023-10-30 11:06:12 浏览: 693
以下是一个找到数组中出现次数最多的元素和输出其出现次数的C语言代码示例:
```c
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7};
int n = sizeof(arr) / sizeof(int);
int max_count = 0;
int max_num = 0;
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
if (count > max_count) {
max_count = count;
max_num = arr[i];
}
}
printf("The element that appears most frequently is %d, which appears %d times.\n", max_num, max_count);
return 0;
}
```
输出结果为:
```
The element that appears most frequently is 7, which appears 5 times.
```
该代码中,我们首先定义了一个整型数组`arr`,并计算出其元素个数`n`。然后,我们遍历数组中的所有元素,对于每个元素,我们又遍历一遍整个数组,统计出该元素在数组中出现的次数。如果该元素出现的次数比当前的最大值`max_count`要大,我们就更新`max_count`和`max_num`的值,分别记录出现次数最多的元素和其出现次数。最后,我们输出`max_num`和`max_count`的值即可。
阅读全文