/*
Program for Searching array of n entered numbers and displays its MODE (Number which has
maximum occurences) using function of return type "int".
Note:
If all numbers occurs only once than the 1st element of the array(i.e: num[0]) will be
displayed as MODE.
*/
#include<iostream>
using namespace std;
int getMode(int[], int);
int countFrequency(int[], int, int);
int main()
{
int size, num[50], mode;
//For Inputting amount of numbers
do
{
cout << "How many numbers u want to sort (Max 50)?\t";
cin >> size;
if (size < 0 || size > 50)
cout << "Invalid Input.......\nEnter number again\n";
} while (size < 0 || size > 50);
//For Inputting Numbers in Array
for (int i = 0; i < size; i++)
{
cout << "Enetr number at [" << i << "] index?\t";
cin >> num[i];
}
mode = getMode(num, size);
//For Displaying Result
cout << "\nMode of the function is:\t " << mode;
cout << endl;
return 0;
}
//Function for searching entered number in array
int countFrequency(int num[], int size,int value)
{
int count = 0;
//For finding index of entered number if it exists
for (int i = 0; i < size; i++)
if (value == num[i])
count++;
return count;
}
int getMode(int num[], int size)
{
int freq = 0, temp, index;
bool flag = 1;
//For calculating Maximum Frequency
for (int i = 0; i < size; i++)
{
/*for insuring that countFrequency is used once for each number even if number occurs
more than once to increase efficiency*/
for (int j = 0; j < i; j++)
if (num[i] == num[j])
{
flag = 0;
break;
}
if (flag) //if it is the first occurence of num[i]
{
temp = countFrequency(num, size, num[i]); //Calculates frequency of
every array element
if (freq < temp)
{
freq = temp;
index = i;
}
}
}
return num[index];
}
OUTPUT
No comments:
Post a Comment