Standard Deviation

My program currently displays the mean and standard deviation of student marks. However, by default (since there are 2 records already with marks of 66 and 78.5), the standard deviation should be 6.25. However, on my program, it displays 1.5 instead.

Here are my codes:

Declarations in main():
1
2
3
4
5
6
7
8
   int totalStudents=2;
    float totalMarks;
    float averageMark;
    string id;
    int found;
    char studentGrade;
    float stdDev;
    float sum;


Function:
1
2
3
4
5
6
7
8
9
10
11
                totalMarks=0;
                sum=0;
                for(int j=0;j<totalStudents;j++)
                    totalMarks+=student[j].studentMark;
                    averageMark=totalMarks/totalStudents;
                    sum+=pow(student[j].studentMark-averageMark,2);
                    stdDev=sqrt(sum/totalStudents);
                    cout << "Number of records: " << totalStudents <<endl;
                    cout << "Mean or average: " << averageMark <<endl;
                    cout << "Standard deviation: " << stdDev <<endl;
                break;


Additional info:
Standard deviation = square root of (sum of x/n)
where
x = (individual student mark/average mark)squared
n = total students

What could be wrong in my codes?
break is not a structure delimiter. It's used to jump to the line immediately after the innermost loop. Your for only loops line 4.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
totalMarks=0;
sum=0;
for(int j=0;j<totalStudents;j++)
{//<-start of body of for cycle 
  totalMarks+=student[j].studentMark;
}//end of body
averageMark=totalMarks/totalStudents;
for(int j=0;j<totalStudents;j++)
{//first cycle was used to get the average
  //you need a second one now:
  sum+=pow(student[j].studentMark-averageMark,2);
}//you have to do the cycle twice mate: no way around that!
stdDev=sqrt(sum/totalStudents);
cout << "Number of records: " << totalStudents <<endl;
cout << "Mean or average: " << averageMark <<endl;
cout << "Standard deviation: " << stdDev <<endl;
//break;<- this line was plain wrong as helios pointed out 
Last edited on
sorry I forgot to mention that the function I posted is a cut-off from my switch statement, and therefore, I forgot to remove the break statement.

Anyways, the problem is solved now. Thank you so much guys, I really appreciate it.
Last edited on
Topic archived. No new replies allowed.