~Write a C++ program that computes the central tendencies mean (average), mode,
ID: 3842892 • Letter: #
Question
~Write a C++ program that computes the central tendencies mean (average), mode, median and the variation: variance, standard deviation and range for a set of numbers given in the data file ArsenicGroundWaterFile.txt.~
~The following data represent (naturally occurring) concentration of arsenic in ground water for a random sample of 102 Northwest Texas wells. Units are parts per billion.~
~The output should be as follows to two decimal places:~
Central Tendency Variation
Mean xxx.xx Variance xxx.xx
Median xxx.xx Std. Dev xxx.xx
Mode xxx.xx Range xxx.xx
__________________________________________
data in text file as follows:
Explanation / Answer
Here is the code for you:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
using namespace std;
double Mean(double numbers[], int count)
{
double mean = 0.0;
for(int i = 0; i < count; i++)
mean += numbers[i];
mean /= count;
return mean;
}
double StandardDeviation(double numbers[], int count)
{
double stdDev = 0;
double average = Mean(numbers, count);
for(int i = 0; i < count; i++)
stdDev += pow((numbers[i] - average), 2); //Sum of (number - average) whole square.
stdDev = sqrt(1/(double)count * stdDev);
return stdDev;
}
double Median(double array[], int size)
{
int middle=0;
double average=0, median=0;
middle = size / 2.0; //Calculates the middle value in the array.
if (size % 2) //If there are odd number of elements in the array.
median = array[middle];
else //If there are even number of elements in the array.
median = (array[middle] + array[middle + 1]) / 2.0;
return median;
}
double Mode(double p[], int n)
{
int counts[n];
for(int i = 0; i < n; i++)
counts[i] = 0;
for(int i = 0; i < n; i++)
counts[p[i]-1]++;
int highestCount = 0;
for(int i = 1; i < 9; i++)
if(counts[i] > counts[highestCount])
highestCount = i;
return highestCount+1;
}
double Variance(double array[], int n)
{
double sum = 0;
double avg = Mean(array, n);
for(int i = 0; i < n; i++)
sum += pow(array[i] - avg, 2);
return sum / n;
}
int main()
{
ifstream fin;
fin.open("ArsenicGroundWaterFile.txt");
double array[102];
for(int i = 0; i < 102; i++)
fin>>array[i];
cout<<"Mean "<<fixed<<setprecision(2)<<Mean(array, 102);
cout<<" Variance "<<fixed<<setprecision(2)<<Variance(array, 102);
cout<<" Median "<<fixed<<setprecision(2)<<Median(array, 102);
cout<<" Std. Dev "<<fixed<<setprecision(2)<<StandardDeviation(array, 102);
cout<<" Mode "<<fixed<<setprecision(2)<<Mode(array, 102);
cout<<endl;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.