# Java Program for Matrix Addition

Here you will get java program for matrix addition.

If you have ever done addition of two matrices in your maths subject then you can easily do this in java also. It can be done in following way.

1. Read two matrices in 2D array a[][] and b[][] respectively inside loop.
2. Now add each element of a[][] with corresponding position element of b[][] and save the result in c[][].
3. Finally display the 2D array c[][].

Note: The addition is possible only when the dimensions of two matrices are equal.

## Java Program for Matrix Addition

```import java.util.Scanner;

public static void main(String args[]){
int i,j,m,n;
Scanner sc = new Scanner(System.in);

System.out.println("Enter number of rows and columns:");
m = sc.nextInt();
n = sc.nextInt();

int a[][] = new int[m][n];
int b[][] = new int[m][n];
int c[][] = new int[m][n];

System.out.println("\nEnter elements of first matrix row wsie:");
for(i = 0; i < m; ++i){
for(j = 0; j < n; ++j){
a[i][j] = sc.nextInt();
}
}

System.out.println("\nEnter elements of second matrix row wsie:");
for(i = 0; i < m; ++i){
for(j = 0; j < n; ++j){
b[i][j] = sc.nextInt();
}
}

for(i = 0; i < m; ++i){
for(j = 0; j < n; ++j){
c[i][j] = a[i][j] + b[i][j];
}
}

//printing the resultant matrix
for(i = 0; i < m; ++i){
for(j = 0; j < n; ++j){
System.out.print(c[i][j] + " ");
}

System.out.print("\n");
}
}
}```

Output

Enter number of rows and columns:
2
2

Enter elements of first matrix row wsie:
2 6
7 9

Enter elements of second matrix row wsie:
12 3
0 4