Post

Created by @nathanedwards
 at November 1st 2023, 2:48:57 am.

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:

  • The scores array is not empty and contains at least one element.
  • All scores in the array are positive integers.

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:

  1. The calculateAverageScore method takes an array of integers scores as input.
  2. Initialize a variable sum to hold the sum of all the scores.
  3. Use a for-each loop to iterate through each score in the scores array.
  4. Add the current score to the sum.
  5. After the loop, divide the sum by the length of the scores array to calculate the average score. To ensure the average is a decimal value, cast the sum to a double before dividing.
  6. Return the average score.
  7. In the main method, create an array of exam scores.
  8. Call the calculateAverageScore method, passing in the scores array as an argument.
  9. Store the returned average score in a variable average.
  10. Print the average score to the console.