Post

Created by @nathanedwards
 at October 31st 2023, 9:32:38 pm.

AP Computer Science Exam Question:

Declare and initialize an array called grades of type int that can store 5 elements. Fill the array with the following grades: 85, 92, 78, 89, and 95. Finally, calculate and print the average of the grades.

Write the code to solve the problem and provide a step-by-step detailed explanation.

public class ArrayGrades {
    public static void main(String[] args) {
        // Declare and initialize an array named grades of type int
        int[] grades = new int[5];

        // Fill the array with given grades: 85, 92, 78, 89, 95
        grades[0] = 85;
        grades[1] = 92;
        grades[2] = 78;
        grades[3] = 89;
        grades[4] = 95;

        // Calculate and print the average of grades
        int sum = 0;
        for (int i = 0; i < grades.length; i++) {
            sum += grades[i];
        }
        double average = (double) sum / grades.length;
        System.out.println("Average grade: " + average);
    }
}

Step-by-step Explanation:

  1. We start by declaring a public class named ArrayGrades with the main method.
  2. Inside the main method, we first declare and initialize an array named grades of type int with a size of 5 using the following syntax: int[] grades = new int[5];. This sets aside memory to store 5 integer values.
  3. Next, we fill the array with the given grades using array indexing. For example, grades[0] = 85; assigns the value 85 to the first element of the array.
  4. After filling the array, we initialize a variable sum to 0, which will be used to compute the sum of all grades.
  5. We use a for loop to traverse each element of the grades array. The loop starts from 0 and continues until i is less than the length of the grades array.
  6. Inside the loop, we add the value of each grade to the sum variable using sum += grades[i];.
  7. Once the loop finishes, we divide the sum by the length of the grades array to calculate the average. We cast the sum to double in order to get a decimal value.
  8. Finally, we print the average grade using System.out.println("Average grade: " + average);.

The output of the code would be:

Average grade: 87.8

This indicates that the average of the grades is approximately 87.8.