Find frequency of smallest value in an array in C++

C++Server Side ProgrammingProgramming

Here we will see how to find the frequency of smallest element in an array. Suppose the array elements are [5, 3, 6, 9, 3, 7, 5, 8, 3, 12, 3, 10], here smallest element is 3, and the frequency of this element is 4. So output is 4.

To solve this we will find the smallest element of the list, then we count the occurrences of first numbers, and that will be the result.

Example

#include<iostream>
using namespace std;
   int min_element(int arr[], int n){
   int min = arr[0];
   for(int i = 1; i<n; i++){
      if(arr[i] < min)
         min = arr[i];
   }
   return min;
   }
   int smallestNumFreq(int *arr, int n) {
      int minimum = min_element(arr, n);
      int count = 0;
   for(int i = 0; i < n; i++){
      if(arr[i] == minimum)
      count++;
   }
   return count;
}
int main() {
   int arr[] = {5, 3, 6, 9, 3, 7, 5, 8, 3, 12, 3, 10};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Frequency of smallest element: " << smallestNumFreq(arr, n);
}

Output

Frequency of smallest element: 4
raja
Published on 01-Nov-2019 07:23:53
Advertisements