1) Develop a C++ function that determines the average value of an array of type double elements
2) Develop a C++ function that determines the variance of an array of type double elements
3) Develop a C++ program that determines and displays the average value and variance of an array of type double elements
const int NUMBER_OF_TEST_SCORES = 19;
double TestScores[NUMBER_OF_TEST_SCORES] = { 180, 122.5,
153, 180, 180, 157.5, 178, 178, 198, 168, 150, 162, 154, 188, 195,
180, 176, 168, 153 };
CODE -
#include<bits/stdc++.h>
using namespace std;
// Function to compute average of the array.
double GetAverage(double array[], int size)
{
float sum = 0;
// This loop computes sum of all elements of the array.
for(int i=0;i<size;i++)
sum += array[i];
return (sum/size); // Returning sum divided by size of array which is equal to average of the array.
}
// Function to compute variance of the array.
double GetVariance(double array[], int size)
{
double sum_sq_diff = 0;
double avg = GetAverage(array,size); // Calling GetAverage function to get the average of the array.
//This loop computes the Sum Squared Differences with mean.
for(int i=0;i<size;i++)
sum_sq_diff += ((array[i] - avg) * (array[i] - avg));
return (sum_sq_diff/size); // Returning sum_sq_diff divided by size of array which is equal to Variance.
}
// Main function to test above functions.
main()
{
const int NUMBER_OF_TEST_SCORES = 19;
double TestScores[NUMBER_OF_TEST_SCORES] = { 180, 122.5, 153, 180, 180, 157.5, 178, 178, 198, 168, 150, 162, 154, 188, 195, 180, 176, 168, 153 };
cout << "The average is " << fixed << setprecision(7) << GetAverage(TestScores,NUMBER_OF_TEST_SCORES) << endl;
cout << "The variance is " << fixed << setprecision(7) << GetVariance(TestScores, NUMBER_OF_TEST_SCORES) << endl;
// setprecision was used so that the values don't get trimmed after decimal places.
}
SCREENSHOT -
Get Answers For Free
Most questions answered within 1 hours.