Post

Created by @nathanedwards
 at November 1st 2023, 4:54:00 pm.

AP Computer Science Exam Question:

You are given a two-dimensional array called matrix of size n x m, where n represents the number of rows and m represents the number of columns. Each cell in the matrix contains an integer value.

Write a Java method called sumOfMatrix that takes in the matrix and returns the sum of all the integer values in the matrix.

Method Signature:

public static int sumOfMatrix(int[][] matrix)

Example:

Input:

int[][] matrix = {
  {1, 2, 3},
  {4, 5, 6},
  {7, 8, 9}
};

Output:

45

Explanation:

In the given example, the provided matrix has 3 rows and 3 columns. The sum of all the integer values in the matrix is calculated as follows:

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45

Therefore, the expected output is 45.

Solution:

The solution requires iterating through each cell in the matrix and adding its value to a running sum. Here's the step-by-step explanation:

  1. Initialize a variable sum to store the running sum and set it to 0.
  2. Use nested for loops to iterate through each row and column in the matrix.
  3. Inside the nested loops, add the value of each cell to the sum variable.
  4. After iterating through all the cells, return the value of sum.
public static int sumOfMatrix(int[][] matrix) {
    int sum = 0;

    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            sum += matrix[i][j];
        }
    }

    return sum;
}

The time complexity of this solution is O(n * m), where n is the number of rows in the matrix and m is the number of columns.