# Matrix addition and subtraction in java

Let’s learn matrix addition and subtraction in java.

## Matrix addition and subtraction in java

A matrix java represents a two-dimensional array. Here user enters the number of rows and columns.

Also read – major features of java

Nested for loop is used to read the input. Outer for loop “m” ranges from 0 to number of rows of the matrix.

Meanwhile inner for loop “n” ranges from 0 to number of columns of matrix. The input is read using “nextInt()” method of class Scanner and stored at x[m][n] and y[m][n] position.

Also read – access modifiers in java

After reading elements, two for loops is used to add two matrices with loop index. Then finally result is stored at z[m][n] position.

```// matrix addition java
import java.util.Scanner;

{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter number of rows : ");
int row = sc.nextInt();
System.out.println("Please enter number of columns : ");
int col = sc.nextInt();

int x[][] = new int[row][col];
int y[][] = new int[row][col];

System.out.println("Please enter first matrix - ");
for(int m = 0; m < row; m++)
{
for(int n = 0; n < col; n++)
{
x[m][n] = sc.nextInt();
}
}

System.out.println("Please enter second matrix - ");
for(int m = 0; m < row; m++)
{
for(int n = 0; n < col; n++)
{
y[m][n] = sc.nextInt();
}
}

// matrix java
int z[][] = new int[row][col];
for(int m = 0; m < row; m++)
{
for(int n = 0; n < col; n++)
{
z[m][n] = x[m][n] + y[m][n];
}
}

System.out.println("The addition of two matrices is - ");
for(int m = 0; m < row; m++)
{
for(int n = 0; n < col; n++)
{
System.out.print(z[m][n] + " ");
}
System.out.println();
}
sc.close();
}
}

```

Output:

Similar to matrix addition in java we can write java program to subtract two matrices,

```// subtraction java
import java.util.Scanner;

public class MatrixSubtractionDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter number of rows : ");
int row = sc.nextInt();
System.out.println("Please enter number of columns : ");
int col = sc.nextInt();

int x[][] = new int[row][col];
int y[][] = new int[row][col];

System.out.println("Please enter first matrix - ");
for(int m = 0; m < row; m++)
{
for(int n = 0; n < col; n++)
{
x[m][n] = sc.nextInt();
}
}

System.out.println("Please enter second matrix - ");
for(int m = 0; m < row; m++)
{
for(int n = 0; n < col; n++)
{
y[m][n] = sc.nextInt();
}
}

int z[][] = new int[row][col];
for(int m = 0; m < row; m++)
{
for(int n = 0; n < col; n++)
{
// subtraction java
z[m][n] = x[m][n] - y[m][n];
}
}

System.out.println("The subtraction of two matrices is - ");
for(int m = 0; m < row; m++)
{
for(int n = 0; n < col; n++)
{
System.out.print(z[m][n] + " ");
}
System.out.println();
}
}
}

```

Output: