How to add 2 matrices in Java

1 Answer

0 votes
public class MyClass {
    public static void main(String args[]) {
        int a[][] = { {1, 0, 2},  
                      {3, 5, 6},  
                      {7, 4, 1} };  
            
        int b[][] = { {1, 0, 1},  
                      {2, 2, 1},  
                      {1, 3, 1} };  

        int rows = a.length;  
        int cols = a[0].length;  
          
        int sum[][] = new int[rows][cols];  
          
        for (int i = 0; i < rows; i++) {  
            for (int j = 0; j < cols; j++) {  
                sum[i][j] = a[i][j] + b[i][j];  
            }  
        }  
          
        for (int i = 0; i < rows; i++) {  
            for (int j = 0; j < cols; j++) {  
               System.out.print(sum[i][j] + " ");  
            }  
            System.out.println();  
        }  
    }
}




 
/*
run:
 
2 0 3 
5 7 7 
8 7 2 
 
*/

 



answered Aug 4, 2021 by avibootz

Related questions

1 answer 259 views
1 answer 207 views
207 views asked Aug 4, 2021 by avibootz
1 answer 205 views
205 views asked Aug 4, 2021 by avibootz
1 answer 203 views
203 views asked Aug 4, 2021 by avibootz
1 answer 248 views
248 views asked May 24, 2017 by avibootz
1 answer 206 views
1 answer 214 views
...