We’d love to hear any feedback or comment from you!

###### Engineering · Computer Science
Question details

THE CODE CALCULATES THE MEAN MEDIAN AND MODE OF THE SET OF NUMBERS THE CODE IS WRITTEN IN C++

PLEASE FIX THE MODE FUNCTION ! SO THAT IT OUTPUTS 0 WHEN THERE ARE NO REPETITIONS IN THE DATASET eg. for 1,2,3,4,5 mode should be zero but it gives 1 !

#include<iostream>
#include<math.h>

using namespace std;

class statistical{
protected:
double *dataArray;
int size;
public:
statistical(double a[], int s){
dataArray = new double[s];
for (int i = 0; i<s; i++){
dataArray[i] = a[i];
}

size = s;
}
virtual void print() = 0;
};
class Mean : public statistical{

public:

Mean(double a[]=0, int s=0) :statistical(a, s){

}
double mean()
{
double Sum = dataArray[0];
for (int i = 1; i < size; ++i) {
Sum += dataArray[i];
}
return Sum / size;
}
void print(){
cout << mean();
}
};
class Median : public statistical{
public:
Median(double a[], int s) :statistical(a, s){
}
void print(){
// Allocate an array of the same size and sort it.
double* Sorted = new double[size];
for (int i = 0; i < size; ++i) {
Sorted[i] = dataArray[i];
}
for (int i = size - 1; i > 0; --i) {
for (int j = 0; j < i; ++j) {
if (Sorted[j] > Sorted[j + 1]) {
double Temp = Sorted[j];
Sorted[j] = Sorted[j + 1];
Sorted[j + 1] = Temp;
}
}
}
// Middle or average of middle values in the sorted array.
double Median = 0.0;
if ((size % 2) == 0) {
Median = (Sorted[size / 2] + Sorted[(size / 2) - 1]) / 2.0;
}
else {
Median = Sorted[size / 2];
}
delete[] Sorted;
cout << Median;
}
};
class Mode : public statistical{
public:
Mode(double a[], int s) :statistical(a, s){
}
void print(){
int* ipRepetition = new int[size];
for (int i = 0; i < size; ++i) {
ipRepetition[i] = 0;
int j = 0;
//bool bFound = false;
while ((j < i) && (dataArray[i] != dataArray[j])) {
if (dataArray[i] != dataArray[j]) {
++j;
}
}
++(ipRepetition[j]);
}
int iMaxRepeat = 0;
for (int i = 1; i < size; ++i) {
if (ipRepetition[i] > ipRepetition[iMaxRepeat]) {
iMaxRepeat = i;
}
}

delete[] ipRepetition;
cout << dataArray[iMaxRepeat];

}
};

int main()
{

int s;
cout<<endl<<"How many numbers do you want to enter:";
cin>>s;
cout<<endl;
cout<<"*********************************"<<endl;
double d[s];
for(int i=0;i<s;i++)
{
cout<<"Enter "<<i+1<<"th number:";
cin>>d[i];

}
Mean mean(d, s);
cout << endl << "Mean is = ";
mean.print();
Mode mode(d, s);
cout << endl << "Mode is = ";
mode.print();
Median median(d, s);
cout<<endl;
cout << "Median is = ";
median.print();
cout << endl;
return 0;
}