>>1283316Building on this anon's work
int sum = 0; // note 1
final int howManyExams = array.length; // note 2
int minScore = array[0]; // note 3
int maxScore = array[0];
for(int i = 0; i < howManyExams ; i++)
{
final int score = array[i:lit]; //note 4
sum += score;
if (score > maxScore) {maxScore = score;} // note 5
else if (score < minScore) {minScore = score;}
}
float average = sum / howManyExams;
1) Assuming it's an int, more efficient than using float here even if the average will be a float.
2) With large arrays, I believe it's generally faster to create an int and look this up once than to look it up on each loop. Something to ask your lecturer or an expert. Note keyword final.
3) By assigning these values we know that they are valid. This allows us to use "if... else if..." later on.
4) Note final. Going to use it several times in the loop so creating it once may be more efficient, idk though. Someone else more knowledgeable can say which is better, three lookups versus one lookup with declaration and assignment.
5) It is faster and more efficient to loop through the array once to assign min, max and calculate the sum than to loop two or even three times doing one thing each time.
Because of how min and max were assigned at declaration, they are valid for even an exam for just one person. After this if a score is highest, it can't be lowest, so use "else if".
Any score < the current min means the first "if" is necessarily false and "else if" catches this low score.
Because the scores in the array are likely to be sorted by student name or code, scores are likely to bounce all over the place. Anytime a new maxScore is found, the first "if" is true and the "else if" line is skipped. Maybe with 100 students, you might assign a new maxScore 25 times. Instead of 200 tests total, 100 for "if higher" and 100 for "if lower", by making the second line "else if lower" you skip this when "if higher" is true. Performing 175 tests is better than 200 tests.