Write a C function called maxfrequency which takes as argume

Write a C++ function called max_frequency which takes as arguments, integer x and returns the frequency of the digits in x, using a single one dimensional array. In case of a tie, the function should return the largest digit. E.g. for the number 3136569, both 3 and 6 appear twice but the function returns 6.

Solution

#include <iostream>
using namespace std;
int max_frequency(int n)
{

//creating an array to calculate the frequency of each digit in a number.

//size of array is 10, a[i] represents the frequency of digit i. Initiazalising all of them to 0.
   int a[] = {0,0,0,0,0,0,0,0,0,0};

int tmp,max;

//Looping through all the digits in the number.

   while(n>0)
   {

//tmp will hold each of the number in each iteration
       tmp = n%10;

//Removing the last digit
       n=n/10;
       a[tmp]++;
   }
   max=0;
   for(int i=1;i<10;i++)
   {
       if(a[i]>=a[max])
       {
           max=i;
       }
   }
   return max;
}
int main()
{
   cout<<max_frequency(3136569)<<endl;
   return 0;
}

Write a C++ function called max_frequency which takes as arguments, integer x and returns the frequency of the digits in x, using a single one dimensional array

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site