java

Sum of Two Matrix in Java

In this tutorial, we are going to see how to calculate the sum of two matrix in Java.

In the below example, we are using two matrices A and B, we have declared these matrices as multidimensional arrays.

Two matrices can simply be added or subtracted if they have similar dimensions, which means they should have a similar number of rows and columns. Here we have two matrices A and B which have the same number of rows and columns. The sum of these matrices will have the same number of rows and columns.
 

 

Java Program to Add Two Matrix
public class Main {
    public static void main(String[] args) {
        int l = 3, c = 3;
        
        // Declare the two multidimensional arrays
        int[][] A = { {1, 5, 3}, {2, 4, 1} , {9, 6, 0}};
        int[][] B = { {2, 7, 3}, {0, 9, 3} , {8, 2, 7} };
        
        // Declare the sum matrix
        int[][] S = new int[l][c];
        for(int i = 0; i < l; i++) {
            for (int j = 0; j < c; j++) {
                S[i][j] = A[i][j] + B[i][j];
            }
        }
        // Print the sum matrix
        System.out.println("The sum of the given matrices is: ");
        for(int i = 0; i < l; i++) {
            for (int j = 0; j < c; j++) {
                System.out.print(S[i][j] + "   ");
            }
            System.out.println();
        }
    }
}

Output:

The sum of the given matrices is: 
3   12   6   
2   13   4   
17   8   7
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *