Question:
Consider the following multidimensional array representing a matrix:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Write a Java code that finds the sum of all the elements in the given matrix and returns the result.
Answer:
To find the sum of all the elements in a multidimensional array (matrix), we can use nested loops to iterate over each element in the matrix and add them to a running sum. Here's the Java code that accomplishes this:
public class MatrixSum {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int sum = 0; // Variable to hold the sum of all elements
// Iterate over each row in the matrix
for (int i = 0; i < matrix.length; i++) {
// Iterate over each column in the current row
for (int j = 0; j < matrix[i].length; j++) {
sum += matrix[i][j]; // Add current element to the sum
}
}
System.out.println("Sum of all elements in the matrix: " + sum);
}
}
Explanation:
matrix
and initializing it with the provided values.int
variable sum
and initialize it to 0. This variable will hold the sum of all the elements in the matrix.matrix[i][j]
to the running sum sum
.sum
, which represents the sum of all the elements in the matrix.Running the code will produce the following output:
Sum of all elements in the matrix: 45
This indicates that the sum of all the elements in the given matrix is 45.