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);
}
}
ArrayGrades
with the main
method.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.grades[0] = 85;
assigns the value 85 to the first element of the array.sum
to 0, which will be used to compute the sum of all grades.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.sum
variable using sum += grades[i];
.grades
array to calculate the average. We cast the sum
to double
in order to get a decimal value.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.