#include <math.h> using namespace std; //This function calculates the mean of array. It has to iterate over //the full length of the array once. double MeanOfArray(double *array, int length) { double sum = 0; for (int i = 0; i < length; ++i) { sum += array[i]; } double mean = sum / double(length); return mean; } //This function calculates the RMS of array. It has to iterate over //the full length of the array once. It also needs the mean, so if we //use the previous function to determine it, we iterate over the full //array twice. double RMSOfArray(double *array, int length, double mean) { double sum = 0; for (int i = 0; i < length; ++i) { sum += pow( (array[i] - mean), 2); } double rms = sqrt( sum / double(length) ); return rms; } //This function calculates the mean and RMS at the same time using the //identity: RMS = <x^2> - <x>^2 //It also is yet another example of passing by reference so that we can //effectively return the mean and rms with one function call. void MeanAndRMSOfArray(double *array, int length, double &mean, double &rms) { double sum = 0; double sum_of_squares = 0; for (int i = 0; i < length; ++i) { sum += array[i]; sum_of_squares += array[i]*array[i]; } mean = sum / double(length); rms = sqrt( sum_of_squares / double(length) - mean*mean); } //Make sure it works with the following.... main() { cout << "Number of points: "; int npoints; cin >> npoints; //This is another example of dynamic memory allocation with "new" double *this_array = new double[npoints]; for (int i = 0; i < npoints; ++i) { cout << "Point " << i << ": "; cin >> this_array[i]; } double mean1 = MeanOfArray(this_array,npoints); double rms1 = RMSOfArray(this_array,npoints,mean1); cout << "Mean, rms are: " << mean1 << " , " << rms1 << endl; double mean2, rms2; MeanAndRMSOfArray(this_array,npoints,mean2,rms2); cout << "Mean, rms are: " << mean2 << " , " << rms2 << endl; //Remember to "delete" anything that was allocated with "new" delete[] this_array; }