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.
public static int sumOfMatrix(int[][] matrix)
Input:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Output:
45
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
.
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:
sum
to store the running sum and set it to 0
.for
loops to iterate through each row and column in the matrix.sum
variable.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.