Find Standard Deviation with C++

I wrote a small C++ program to calculate the mean and standard deviation of a given data set. Here it is:

#include <iostream>
#include <cmath>
using namespace std;

int main (int argc, char* argv[])
{
	int number_of_items;
	cout << "How many pieces of data are in the list? ";
        cin >> number_of_items;
	float list[number_of_items];

	// get all the data items
	cout << "Please enter the data:" << endl;
	int i;
	for (i = 1; i <= number_of_items; i++)
	{
		cout << i << ". "; 		cin >> list[i];
	}

	// find the mean (average) of the data
	float xbar = 0;
	for (i = 0; i <= number_of_items; i++)
		xbar = xbar + list[i];

	xbar = xbar / number_of_items;
	cout << "The mean (average) is " << xbar << "." << endl;

	// find the standard deviation
	float numerator = 0;
	float denominator = number_of_items;

	for (i = 1; i <= number_of_items; i++)
		numerator = numerator + pow((list[i] - xbar), 2);

	float standard_deviation = sqrt (numerator/denominator);
	cout << "The standard deviation for the given data is "
		 << standard_deviation << "." << endl;

	return 0;
}
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: