I am trying to output the overall class average on a test using a program which makes use of arrays. The program is meant to be for a class of 12 students. When I try to input all data I need, I don't get the average for the class as a whole. The problem obviously lies in the average calculator itself but seeing as I am a beginner I have little clue how to fix it. Any help would be appreciated. Just to reiterate, I am looking for a solution on how to fix my average calculator to give the class average as an overall. I have entered my code below. I hope I have been specific.
string[] studentnames = new string[12];
int[] testscore = new int[12];
int i;
int index;
double average;
int total = 0;
//title
Console.Write("\n\nStudent lists:\n");
Console.Write("******************\n");
//asks user to input names
Console.Write("Enter student names:\n");
for (i = 1; i < 12; i++)
{
Console.Write("Student name {0} : ", i);
studentnames[i] = (Console.ReadLine());
//asks user to enter student's test score
Console.Write("Please enter their test score: ");
testscore[i] = Convert.ToInt32(Console.ReadLine());
}
//outputs all values user has entered
Console.WriteLine("\nStudent marks: ");
for (i = 1; i < 12; i++)
{
Console.WriteLine("Name: ");
Console.WriteLine("{0} ", studentnames[i]);
Console.WriteLine("Test score: ");
Console.WriteLine("{0} ", testscore[i]);
}
for (index = 1; index < 12; index++)
{
total = total + testscore[index];
average = total / 12;
Console.WriteLine("The class average was: " + average);
}
Console.ReadKey();
The division by the total needs to be after the for
loop.
This:
for (index = 1; index < 12; index++)
{
total = total + testscore[index];
average = total / 12;
Console.WriteLine("The class average was: " + average);
}
Needs to become:
for (index = 1; index < 12; index++)
{
total = total + testscore[index];
}
average = ((double)total) / 12;
Console.WriteLine("The class average was: " + average);
Another problem: your for
loops start at index 1. C# uses 0 based indexing. I assume you are trying to calculate the average for 12 students, not 11.
Also, for the love of god please stop writing the number 12
. If you absolutely must hard-code it, use a constant.
Edit: I've updated my answer to account for flydog's comment
@yeok: Also, if you want your average to be a
double
, don't divide two integers - it will result in an integer (for example, if your total is 825, when you do integer division of 825 by 12, you will get 68, not 68.75). Change the average calculation toaverage = (double) total / 12
; since the dividend is a double, the result will be a double. Or, you could just declaretotal
to be a double to start with:double total = 0.0;