AP Computer Science Exam Question - Multidimensional Arrays
Consider the following scenario:
You have been given a dataset that contains the scores of students in a classroom for three different subjects: Math, Science, and English. The dataset is represented using a two-dimensional array where each row represents a student and each column represents a subject.
int[][] scores = {
{90, 85, 92},
{78, 86, 80},
{95, 88, 89},
{82, 92, 86},
{88, 90, 94}
};
Write a program in Java that calculates and outputs the average score for each subject.
Implement the following method:
/**
* Calculates the average score for each subject.
*
* @param scores a two-dimensional array representing the scores of students
* @return an array of doubles with the average score for each subject
*/
public static double[] calculateAverage(int[][] scores) {
// Write your code here
}
In your main
method, call the calculateAverage
method and print the resulting average scores for each subject.
Exemplary Output:
Average scores:
Math: 86.6
Science: 88.2
English: 88.2
Provide your implementation for the calculateAverage
method, including a step-by-step explanation of your solution.
public static double[] calculateAverage(int[][] scores) {
int numStudents = scores.length;
int numSubjects = scores[0].length;
double[] averages = new double[numSubjects];
// Iterate over each column (subject)
for (int subject = 0; subject < numSubjects; subject++) {
int sum = 0;
// Calculate the sum of scores for the current subject
for (int student = 0; student < numStudents; student++) {
sum += scores[student][subject];
}
// Calculate the average for the current subject
double average = (double) sum / numStudents;
// Store the average in the corresponding index of the averages array
averages[subject] = average;
}
return averages;
}
Explanation:
scores
array, which represents the number of rows.numSubjects
to the length of the first row, which represents the number of subjects.averages
with a length equal to the number of subjects to store the average scores.subject
variable ranging from 0 to numSubjects-1
.sum
to 0 to calculate the sum of scores for the current subject.student
variable ranging from 0 to numStudents-1
.sum
variable.sum
by the number of students, casting the result to a double
to ensure accuracy in the division.averages
array.averages
array.main
method, we call the calculateAverage
method and store the returned array of averages in a variable.Note: Make sure to include proper indentation and imports necessary to execute the code successfully.