I have setup an array and i have calculated the sum of my array. Now i need to find standard deviation of the numbers entered in my array. here is my code

#include <iostream>

using namespace std;
int main()
{
    int i=0, count, maxSize = 36;
    double arr[36]; 
    double number;

 
    
	cout << "Enter number ";
	cin >> number;

	while ((i < maxSize) && (number != -99))
	{   arr[i] = number;
		i++;
		cout << "Enter another number ";
		cin >> number;
    }
    count = i;
 
    cout << "Numbers entered are " << endl;
    for (int j = 0; j < count; j++)
        cout << arr[j] << " " ; 
    cout << endl;
    
 double sum = 0;
  for ( int i = 0; i < 36; i++ ) 
   sum += arr[i]; 
   cout<<"Average of data is  "<< sum / 36 <<endl;
   

 
 system("pause");
   return 0;
}

Is this correct

#include <iostream>
#include <cmath>

using namespace std;
int main()
{
    int i=0, count, maxSize = 35;
    double arr[35]; 
    double number;
    int Average=0;
 
    
	cout << "Enter number ";
	cin >> number;

	while ((i < maxSize) && (number != -99))
	{   arr[i] = number;
		i++;
		cout << "Enter another number ";
		cin >> number;
    }
    count = i;
 
    cout << "Numbers entered are " << endl;
    for (int j = 0; j < count; j++)
        cout << arr[j] << " " ; 
    cout << endl;
    
 double sum = 0;
  for ( int i = 0; i < 35; i++ ) 
   sum += arr[i]; 
   cout<<"Average of data is  "<< sum / 35 <<endl;
   cin>>Average;
    
    double s_dev = 0;    
    s_dev = sqrt( (( pow(sum,2.0)) -(( 1.0/count) * (pow(sum,2.0))))/ (count -1.0));  
            
       cout << " The standard deviation is:  " << s_dev << endl; 


 
 system("pause");
   return 0;
}

Edited 6 Years Ago by a-hall: n/a

I notice that you are using a lot of "magic numbers" for your array sizes, set sizes, etc... If you are familiar with constants, you may want to consider adding a few to minimize your chances of having issues.
This:

const int SET_SIZE = 15;
const int RAND_RANGE = 10;

int main() {
  int anArray[SET_SIZE] = {0};

  for (int i = 0; i < SET_SIZE; ++i)
    anArray[i] = (rand() % RAND_RANGE);

  double sum = 0.0;
  for (int j = 0; j < SET_SIZE; ++j)
    sum += anArray[j];

  double avg = (sum / SET_SIZE);

  return 0;
}

Is more reliable, and less error-prone, than this:

int main() {
  int anArray[15] = {0};

  for (int i = 0; i < 15; ++i)
    anArray[i] = (rand() % 10);

  double sum = 0.0;
  for (int j = 0; j < 15; ++j)
    sum += anArray[j];

  double avg = (sum / 15);

  return 0;
}

because you only need to change the value(s) in one location rather than several.

Q.What happens if your set size changes from 15 to 10 and you forget to change, for example, the 15 on Line 4?

A.Your program crashes with a segmentation fault, then you come here and ask why your program keeps crashing.

This article has been dead for over six months. Start a new discussion instead.