Check frequency for value inside an array - C++ Data Type

C++ examples for Data Type:Array

Description

Check frequency for value inside an array

Demo Code

#include <iostream> 
#include <iomanip> 
using namespace std;

int main()//from w  w  w . j  a v  a 2 s .c  o  m
{
  // define array sizes 
  const int responseSize = 50; // size of array responses 
  const int frequencySize = 6; // size of array frequency 

                 // place survey responses in array responses 
  const int responses[responseSize] = {
    1, 2, 5, 4, 3, 5, 2, 1, 3, 1, 4, 3,
    2, 1, 3, 1, 4, 3, 1, 2, 5, 4, 3, 5,
    3, 3, 2, 3, 3, 2, 2, 5 };

  // initialize frequency counters to 0 
  int frequency[frequencySize] = {};

  // use that value as frequency subscript to determine element to increment 
  for (int answer = 0; answer < responseSize; ++answer)
    ++frequency[responses[answer]];

  cout << "Rating" << setw(17) << "Frequency" << endl;

  // output each array element's value 
  for (int rating = 1; rating < frequencySize; ++rating) {
    cout << setw(6) << rating << setw(17) << frequency[rating] << endl;
  }
}

Result


Related Tutorials