Need help with standard deviation function. Something seems to be wrong with the SD value once I run the program


#include<iostream>
#include<iomanip>
#include <cmath>
#include<vector>
#include<algorithm>
#include<stdio.h>
#include<conio.h>

double Mean (int [], int, double &, double &);
double standardDeviation (int [], int,double &, double &, double &, double &);
int findMedian (int [ ] , int, double&);
void Sort(int * , int);

int main()
{
int ar[100],n,i,min=0,max=0; //Initializing variables
double avg=0.0,median=0.0, sum=0.0, sum2=0.0, sD=0.0;
printf("How many numbers do you want to use? "); //Gets the size of the array
scanf("%d",&n);

printf("\nPlease enter each number and press the enter key. \n"); //Gets the contents of the array
for(i=0;i<n;i++)
{
scanf("%d",&ar[i]);
}
min=ar[0]; //Traverses through the array and finds the smallest number
for(i=0;i<n;i++)
{
if(ar[i]<=min)
{
min=ar[i];
}
}
max=ar[0]; //Traverses through the array and finds the largest number
for(i=0;i<n;i++)
{
if(ar[i]>=max)
{
max=ar[i];
}
}

printf("\n\t The smallest number is: %d",min);
printf("\n\t The largest number is: %d",max);

Mean(ar, n, sum, avg);
printf("\n\t The mean is: %f",avg);

sD = standardDeviation(ar,n,sum,sum2,avg,sD);
printf("\n\t The standard deviation is: %d",sD);

findMedian(ar, n, median);
printf("\n\t The median of your unsorted list is: %f",median);

Sort(ar, n);
printf("\n\t The numbers listed in ascending order are: ");
for(i=0;i<n;i++)
{
printf("%d", ar[i]);
printf(" ");
}
getch();
}

double Mean (int ar[], int n, double &sum, double &avg)
{
for(int i=0;i<n;i++) //Finds the sum of the array
{
sum= sum+ ar[i];
avg= sum/ float(n);
}
return avg;
} // Function for mean

double standardDeviation (int ar[], int n, double &sum, double &sum2, double &avg, double &sD)
{
for(int i=0;i<n;i++) //Finds the sum of the array
{
sum= sum+ ar[i];
}
avg= sum/ float(n);

for ( int i = 0; i <=n; i++ )
{
sum2 += pow(ar[i]-avg,2);
}
sD= sqrt((sum2/n));
return sD;
}

int findMedian(int ar[ ] , int n, double &median)
{
if (n%2==1)
{ /* if there is an odd number of elements I want n/2 - 1 */
median = ar[n/2];
return median;
}
else
median = ( ar[n/2] + ar[n/2 - 1] ) / 2;
return median; /* otherwise I want the average of n/2 -1 and n/2*/
}

void Sort(int *array, int n)
{
bool swapped = true;
int j = 0;
int tmp;
while (swapped)
{
swapped = false;
j++;
for (int i = 0; i < n - j; i++)
{
if (array[i] > array[i + 1])
{
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
}
A couple things. sum is not 0 when standardDeviation is entered.

The valid indices for an array of n elements is 0 to n-1, so the second for loop in standardDeviation accesses memory it shouldn't.

In printf("\n\t The standard deviation is: %d",sD); %d is not a correct format specifier for a variable of type double. Why are you using C input and output anyway?
I was under the assumption that I was doing things the correct way? I'm a little rusty on programming I haven't done it since undergraduate. How can I resolve the issue?

I changed my code and now i don't have sum initialized as 0.0, I also changed the specifier to %lf, should I change it from C?
Last my for loop now reads:

for ( int i = 0; i <=n; i++ )
{
sum2 += pow(ar[i]-avg,2);
}
sD= sqrt(sum2/(n-1));
return sD;

I am getting a new value that looks a lot nicer now however it is still wrong, how can I resolve the issue?
Put your code inside code tags, post it together with your input and results.
It will be much easier to help you then.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include<iostream>
#include<iomanip>
#include <cmath>
#include<vector>
#include<algorithm>
#include<stdio.h>
#include<conio.h>

using namespace std; 

//Prototypes
double Mean (int [], int, double &, double &);	
double standardDeviation (int [], int, double &, double &, double &, double &);
int findMedian (int [ ] , int, double&);
void Sort(int * , int);

int main()	//Main Function
{
     int ar[100],n,i,min=0,max=0;	//Initializing variables
     double avg=0.0,median=0.0, sum, sum2, sD;
     printf( "How many numbers do you want to use? ");	//Gets the size of the array
     scanf("%d",&n);

     printf("\nPlease enter each number and press the enter key. \n");	//Gets the contents of the array
     for(i=0;i<n;i++)
     {
           scanf("%d",&ar[i]);
     }
     min=ar[0];	//Traverses through the array and finds the smallest number
     for(i=0;i<n;i++)
     {
           if(ar[i]<=min)
           {
                 min=ar[i];
           }
     }
	 max=ar[0];	//Traverses through the array and finds the largest number
     for(i=0;i<n;i++)
     {
           if(ar[i]>=max)
           {
                 max=ar[i];
           }
     }
    	  	  
     printf("\n\t The smallest number is: %d",min);
     printf("\n\t The largest number is: %d",max);
     
     Mean(ar, n, sum, avg);
     printf("\n\t The mean is: %lf",avg);
	
	 sD = standardDeviation(ar,n,sum,sum2,avg,sD);
     printf("\n\t The standard deviation is: %lf",sD);
   
	 findMedian(ar, n, median);
	 printf("\n\t The median of your unsorted list is: %lf",median); 
	        
     Sort(ar, n);
	 printf("\n\t The numbers listed in ascending order are: ");
	 for(i=0;i<n;i++)
     {
		printf("%d", ar[i]);
		printf(" ");
     } 
     getch();
}

double Mean (int ar[], int n, double &sum, double &avg)	
{
	 for(int i=0;i<n;i++)	//Finds the mean of the array 
     {
      	sum= sum+ ar[i];
      	avg= sum/ float(n);
     }
return avg;
}	

double standardDeviation (int ar[], int n, double &sum, double &sum2, double &avg, double &sD)
{
	 for(int i=0;i<n;i++)	//Finds the standard deviation of the array 
     {
      	sum= sum+ ar[i];
     }
	 avg= sum/ float(n);
      	
	for ( int i = 0; i <=n; i++ )
	{
		sum2 += pow(ar[i]-avg,2);
	}
	sD= sqrt(sum2/(n-1));
	return sD;
} 

int findMedian(int ar[ ] , int n, double &median)
{
 		if (n%2==1) 
		{ 				// if there is an odd number of elements I want n/2 
 		median = ar[n/2];
 		return median;
 	    }
 		else
 		median = ( ar[n/2] + ar[n/2 - 1] ) / 2;
 		return median; 	//otherwise I want the average of n/2 -1 and n/2
}

void Sort(int *array, int n)
{						//Sorts the array in ascending order
      bool swapped = true;
      int j = 0;
      int tmp;
      while (swapped) 
	  {
            swapped = false;
            j++;
            for (int i = 0; i < n - j; i++) 
			{
                  if (array[i] > array[i + 1]) 
				  {
                        tmp = array[i];
                        array[i] = array[i + 1];
                        array[i + 1] = tmp;
                        swapped = true;
                  }
            }
      }
}


Input/Output:
How manynumbers do you want to use? 5

Please enter each number and press the enter key.
3
4
5
1
2

The smallest number is: 1
The largest number is: 5
The mean is: 3.000000
The standard deviation is: 4.769696
The median of your unsorted list is: 5.000000
The numbers listed in ascending order are: 1 2 3 4 5


The answer for standard deviation should be 1.5811

Thanks in advance for all your help!!




I changed my code and now i don't have sum initialized as 0.0


I wasn't suggesting that you shouldn't initialize it, in fact they must be initialized if you expect the other functions to continue working, the way you have it designed.

I was suggesting that if sum isn't 0 (and it isn't) when you enter standardDeviation and you don't set it to 0, then the calculation will be wrong (and it is.) (And you're still accessing memory you shouldn't in the second for loop.)

The use of all these references is silly. None of what you're passing as references now should be passed as references.

For instance, it would make a lot more sense to write mean as:

1
2
3
4
5
6
7
8
double mean(int array[], unsigned n)
{
    int sum = 0 ;
    for ( unsigned i=0; i<n; ++i )
        sum += array[i] ;

    return sum / static_cast<double>(n) ;
}
Is there someone that can help me to figure out how to write the standard deviation function correctly? @Cire you said that I am still accessing memory I shouldn't in the second for loop,How can I resolve this? What should I look to change?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include<iostream>
#include<iomanip>
#include <cmath>
#include<vector>
#include<algorithm>
#include<stdio.h>
#include<conio.h>

using namespace std; 

//Prototypes
double Mean (int [], unsigned);	
double standardDeviation (int [], unsigned);
int findMedian (int [ ] , unsigned);
void Sort(int * , unsigned);

//Initializing variables
int ar[100],n,i;	
double avg=0.0,median=0.0, sum, sum2, sD;

int main()	//Main Function
{
     int min=0,max=0;
     
	 cout<<"How many numbers do you want to use? ";	//Gets the size of the array
     cin>>n;
	 
     cout<<endl<<"Please enter each number and press the enter key."<<endl;	//Gets the contents of the array
     for(i=0;i<n;i++)
     {
		   cin>>ar[i];     	
     }
     min=ar[0];	//Traverses through the array and finds the smallest number
     for(i=0;i<n;i++)
     {
           if(ar[i]<=min)
           {
                 min=ar[i];
           }
     }
	 max=ar[0];	//Traverses through the array and finds the largest number
     for(i=0;i<n;i++)
     {
           if(ar[i]>=max)
           {
                 max=ar[i];
           }
     }
    	  	  
     cout<<endl<<" 	The smallest number is: "<<min<<endl;
     cout<<" 	The largest number is: "<<max<<endl;
          
     Mean(ar, n);
     cout<<" 	The mean is: "<<avg<<endl;
	
	 sD = standardDeviation(ar,n);
     cout<<" 	The standard deviation is: "<<sD<<endl;
	   
	 findMedian(ar, n);
	 cout<<" 	The median of your unsorted list is: "<<median<<endl;
	        
     Sort(ar, n);
     cout<<" 	The numbers listed in ascending order are: ";
	 for(i=0;i<n;i++)
     {
		cout<< ar[i]<<" ";
     } 
}

double Mean(int ar[], unsigned n)
{
    int sum = 0 ;
    for ( int i=0; i<n; i++ )
        sum += ar[i] ;

    return avg=sum / static_cast<double>(n) ;
} 
	

double standardDeviation (int ar[], unsigned n)
{
	 for(int i=0;i<n;i++)	//Finds the standard deviation of the array 
     {
     		sum= sum+ ar[i];
     }
	 avg= sum/ float(n);
      	
	for ( int i = 0; i <=n; i++ )
	{
		sum2 += pow(ar[i]-avg,2);
	}
	sD= sqrt(sum2/(n-1));
	return  static_cast<double>(sD);
} 

int findMedian(int ar[ ] , unsigned n)
{
 		if (n%2==1) 
		{ 				// if there is an odd number of elements I want n/2 
 		median = ar[n/2];
 		return median;
 	    }
 		else
 		median = ( ar[n/2] + ar[n/2 - 1] ) / 2;
 		return  static_cast<double>(median); 	//otherwise I want the average of n/2 -1 and n/2
}

void Sort(int *array, unsigned n)
{						//Sorts the array in ascending order
      bool swapped = true;
      int j = 0;
      int tmp;
      while (swapped) 
	  {
            swapped = false;
            j++;
            for (int i = 0; i < n - j; i++) 
			{
                  if (array[i] > array[i + 1]) 
				  {
                        tmp = array[i];
                        array[i] = array[i + 1];
                        array[i + 1] = tmp;
                        swapped = true;
                  }
            }
      }
}


Input/Output:
How manynumbers do you want to use? 5

Please enter each number and press the enter key.
3
4
5
1
2

The smallest number is: 1
The largest number is: 5
The mean is: 3.000000
The standard deviation is: 2.17945
The median of your unsorted list is: 5.000000
The numbers listed in ascending order are: 1 2 3 4 5


The answer for standard deviation should be 1.5811

Thanks in advance for all your help!!
Hello.

The code looks nice, just a few minor bugs here and there. I calculated the standard deviation of your numbers and the answer I got is sqrt(2). I will post my solution here and then I will check an on-line standard deviation calculator to see if my answer is right.

Nvm it works now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include<iostream>
#include <cmath>
#include<algorithm>

using namespace std; 

//Prototypes
double Mean (int [], int);	
double standardDeviation (int [], int, double);


int main()	//Main Function
{
  int n;	
  double avg = 0;
  double median = 0;
  double median2 = 0;
  double sD;
  int min=0;
  int max = 0;
  
  cout<<"How many numbers do you want to use? ";	//Gets the size of the array
  cin>>n;
  
  int *ar = new int[n];
  int tempAr[n];
  
  cout<<endl<<"Please enter each number and press the enter key."<<endl;	//Gets the contents of the array
  for(int i = 0; i < n; ++i)
  {
    cin>>ar[i];
    tempAr[i] = ar[i]; //a temp array
  }
  
  sort (tempAr, tempAr+n);//Sort into ascending order
  min=tempAr[0]; //Traverses through the array and finds the smallest number
  
  max=tempAr[n -1]; //Traverses through the array and finds the largest number
  
  
  cout<<"\tThe smallest number is: "<<min<<endl;
  cout<<"\tThe largest number is: "<<max<<endl;
  
  avg = Mean(ar, n);
  cout<<"\tThe mean is: "<<avg<<endl;
  
  sD = standardDeviation(ar, n, avg);
  cout<<"\tThe standard deviation is: "<< sD<<endl;
  
  int med;
  int med2;
  if (n % 2 != 0)
  {
    med = (n/2);
    median = ar[med];
    median2 = tempAr[med];
  }
  else
  {
    med = (ar[n/2] + ar[(n/2) + 1])/2;
    med2 = (tempAr[n/2] + tempAr[(n/2) + 1])/2;
    median = med;
    median2 = med2;
  }
  cout<<"\tThe median of your unsorted list is: "<<median<<endl;
  
  cout<<"\tThe median of your sorted list is: "<<median2<<endl;
  
  cout<<"\tThe numbers listed in ascending order are: ";
  for(int k = 0; k < n; ++k)
    cout<< tempAr[k]<<" ";
  cout <<endl;
}

double Mean(int *ar, int n)
{
  int sum = 0 ;
  for ( int i=0; i<n; i++ )
    sum += ar[i] ;
  
  return sum / n ;
} 


double standardDeviation (int ar[], int n, double avg)
{
  double temp[n];
  double sum2 = 0;
  double sum3 = 0;
  
  for(int i=0; i<n; i++)	//Finds the standard deviation of the array 
    temp[i] = pow((ar[i] - avg), 2);
  
  for (int a = 0; a < n; ++a)
    sum2 += temp[a];
  
  sum3 = sum2/(n-1);
  
  return sqrt(sum3);
}



$ ./File
How many numbers do you want to use? 5

Please enter each number and press the enter key.
3
4
5
2
1
	The smallest number is: 1
	The largest number is: 5
	The mean is: 3
	The standard deviation is: 1.58114
	The median of your unsorted list is: 5
	The median of your sorted list is: 3
	The numbers listed in ascending order are: 1 2 3 4 5
Last edited on
Thank you so much Smac89!!!
Now mark thread as solved
Topic archived. No new replies allowed.