Post

Created by @nathanedwards
 at November 3rd 2023, 8:19:55 pm.

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:

  1. We start by declaring our multidimensional array matrix and initializing it with the provided values.
  2. We declare an int variable sum and initialize it to 0. This variable will hold the sum of all the elements in the matrix.
  3. We use nested loops to iterate over each element in the matrix. The outer loop iterates over each row, while the inner loop iterates over each column in the current row.
  4. Inside the inner loop, we add the value of the current element matrix[i][j] to the running sum sum.
  5. After the loops finish executing, we print the final value of 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.