You are tasked with creating a program that analyzes student grades using multidimensional arrays. Each row in the array represents a student, and each column represents a different assignment. Each element in the array is a grade for that assignment.
Write a method called calculateAverage
that takes in a 2D integer array grades
and returns an array of doubles, where each element represents the average score for each student. The grades
array has the following format:
int[][] grades = {
{85, 92, 78, 90}, // student 1
{90, 76, 85, 88}, // student 2
{88, 84, 92, 76}, // student 3
};
Use the following method signature:
public static double[] calculateAverage(int[][] grades)
Example:
int[][] grades = {
{85, 92, 78, 90},
{90, 76, 85, 88},
{88, 84, 92, 76},
};
double[] averages = calculateAverage(grades);
Output:
averages = {86.25, 84.75, 85.0}
To calculate the average score for each student, we need to iterate over each row (student) in the grades
array and calculate the average of the scores in that row.
Here is the step-by-step explanation of the calculateAverage
method:
Initialize an empty array averages
of type double[]
with a length equal to the number of rows in the grades
array.
Iterate over each row (student) in the grades
array using a for
loop. Let's use i
as the loop counter variable for rows.
Inside the loop, calculate the sum of the scores in the current row using a nested for
loop. Let's use j
as the loop counter variable for columns. Initialize a variable sum
to 0 before the nested loop.
Inside the nested loop, add the element grades[i][j]
to the sum
.
After the nested loop, calculate the average score for the current row by dividing the sum
by the number of columns in the grades
array. Store the average in the corresponding index of the averages
array (averages[i] = sum / grades[i].length;
).
After the outer loop finishes, return the averages
array.
public static double[] calculateAverage(int[][] grades) {
double[] averages = new double[grades.length];
for (int i = 0; i < grades.length; i++) {
int sum = 0;
for (int j = 0; j < grades[i].length; j++) {
sum += grades[i][j];
}
averages[i] = sum / (double)grades[i].length;
}
return averages;
}
By calling the calculateAverage
method with the provided example array grades
, we get the expected output {86.25, 84.75, 85.0}
. This means that the average score for student 1 is 86.25, for student 2 is 84.75, and for student 3 is 85.0.