Question:
In a math class, the teacher wants to create a method to calculate the average score of a student in a set of exams. Write a Java method named calculateAverageScore
that takes an array of integers scores
as input and returns the average score as a double value.
The calculateAverageScore
method should have the following signature:
public static double calculateAverageScore(int[] scores)
Assumptions:
scores
array is not empty and contains at least one element.Example:
For an array scores = {80, 90, 70, 85, 95}
, the method calculateAverageScore(scores)
should return 84.0
.
Implement the calculateAverageScore
method and use it to calculate the average score of the given array of exam scores.
Answer:
public class MathClassMethods {
public static double calculateAverageScore(int[] scores) {
int sum = 0;
for (int score : scores) {
sum += score;
}
return (double) sum / scores.length;
}
public static void main(String[] args) {
int[] scores = {80, 90, 70, 85, 95};
double average = calculateAverageScore(scores);
System.out.println("Average score: " + average);
}
}
Step-by-Step Explanation:
calculateAverageScore
method takes an array of integers scores
as input.sum
to hold the sum of all the scores.scores
array.scores
array to calculate the average score. To ensure the average is a decimal value, cast the sum to a double before dividing.main
method, create an array of exam scores.calculateAverageScore
method, passing in the scores array as an argument.average
.