## Saturday, 28 September 2019

### Java Program to Perform Matrix Addition and Subtraction

In the previous post, written code for matrix transpose. In the current post, I have written a java program to perform a simple matrix addition and subtraction.

Below is the source code of the Java Program to Perform Matrix Multiplication,

```package com.example.demo;

public static void main(String[] args) {

int[][] a = { { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } };
int[][] b = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

int rows = 3;
int columns = 3;

int[][] c = new int[rows][columns];

for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}

System.out.println("The sum of the two matrices is");

for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}

for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
c[i][j] = a[i][j] - b[i][j];
}
}

System.out.println("The subtraction of the two matrices is");

for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}

}
}
```

Output:--
The sum of the two matrices is
5 7 9
11 13 15
17 19 21
The subtraction of the two matrices is
3 3 3
3 3 3
3 3 3

Related Posts:--