Write a program that generate 20 random integers between 10 and 90 and then stores
it in an array. Your goal is to find:
• Mean
• Median
• Mode
For this question, provide switch menu to user in order to select one of the option from
above.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void ArrayS(int[]);
void Display(int[]);
void CalculateMean(int[]);
void CalculateMedian(int[]);
void CalculateMode(int[]);
int main()
{
int Array[20];
char option;
srand(time(0));
cout << "Initial array: ";
for(int x=0;x<20; x++)
{
Array[x]=(int)rand()%81+10;
cout << Array[x]<<' ';
}
cout << endl;
ArrayS(Array);
do{
cout << endl;
cout << "1.Mean\n2.Median\n3.Mode\n4.Quit" << endl;
option = cin.get();
cin.get();
switch (option)
{
case '1': CalculateMean(Array); break;
case '2': CalculateMedian(Array); break;
case '3': CalculateMode(Array); break;
case '4': return 0; break;
}}while(!(option=='4'));
return 0;
}
void ArrayS(int *Array)
{
int x,j,k;
for(x=0; x<19; x++)
{
for(j=x+1; j<20; j++)
{
if(Array[x]>Array[j])
{
k=Array[x];
Array[x]=Array[j] ;
Array[j]=k;
}
}
}
};
void Display(int *Array)
{
cout << "Array: ";
for(int x=0;x<20; x++)
{
cout << Array[x];
cout << ' ';
}
cout << endl;
};
void CalculateMean(int *Array)
{
int summ = 0;
for(int x=0; x<19; x++) summ+=Array[x];
cout << "Mean = " << summ/20 << endl;
};
void CalculateMedian(int *Array)
{
cout << "Median = " << (Array[9]+Array[10])/2 << endl;
};
void CalculateMode(int *Array)
{
int num=-1;
int CountMax=0;
int Count=0;
int x,j;
for(x=0; x<19; x++)
{
Count=0;
for(j=x+1; j<20; j++)
{
if(Array[x]==Array[j])
{
Count++;
}
}
if(Count>CountMax)
{
CountMax=Count;
num=Array[x];
}
}
if(num > -1)
{
cout << "Mode = ";
for(x=0; x<19; x++)
{
Count=0;
for(j=x+1; j<20; j++)
{
if(Array[x]==Array[j])
{
Count++;
}
}
if(Count==CountMax)
{
cout << Array[x] << ' ';
}
}
cout << endl;
}
else cout << "No mode" << endl;
};
Comments
Leave a comment