Addition of Two Matrices
This program adds two matrices element wise.
Problem Statement
Write a Java program to add two 3x3 matrices.
Source Code
| 1 | public class MatrixAddition { |
| 2 | public static void main(String[] args) { |
| 3 | int[][] A = {{1,2,3},{4,5,6},{7,8,9}}; |
| 4 | int[][] B = {{9,8,7},{6,5,4},{3,2,1}}; |
| 5 | int[][] C = new int[3][3]; |
| 6 | for(int i=0;i<3;i++){ |
| 7 | for(int j=0;j<3;j++){ |
| 8 | C[i][j] = A[i][j] + B[i][j]; |
| 9 | } |
| 10 | } |
| 11 | for(int i=0;i<3;i++){ |
| 12 | for(int j=0;j<3;j++){ |
| 13 | System.out.print(C[i][j]+" "); |
| 14 | } |
| 15 | System.out.println(); |
| 16 | } |
| 17 | } |
| 18 | } |
Program Output
10 10 10 10 10 10 10 10 10
Explanation
Two matrices A and B are initialized, and a result matrix C of the same dimensions is filled by nested loops that add corresponding elements, demonstrating matrix addition and how multidimensional arrays can be manipulated element wise.