使用C ++在数组中查找数字的频率。

假设我们有一个数组。有n个不同的元素。我们必须检查数组中一个元素的频率。假设A = [5、12、26、5、3、4、15、5、8、4],如果我们尝试找到5的频率,则为3。

为了解决这个问题,我们将从左边扫描数组,如果该元素与给定的编号相同,则增加计数器,否则转到下一个元素,直到数组耗尽。

示例

#include<iostream>
using namespace std;
int countElementInArr(int arr[], int n, int e) {
   int count = 0;
   for(int i = 0; i<n; i++){
      if(arr[i] == e)
         count++;
   }
   return count;
}
int main () {
   int arr[] = {5, 12, 26, 5, 3, 4, 15, 5, 8, 4};
   int n = sizeof(arr)/sizeof(arr[0]);
   int e = 5;
   cout << "Frequency of " << e << " in the array is: " << countElementInArr(arr, n, e);
}

输出结果

Frequency of 5 in the array is: 3