Java Program to subtract two matrices
Program
import java.util.Scanner;
class SubtractMatrix
{
public static void main(String[] args) {
int i, j;
int row, col;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows for both matrix:\t");
row = sc.nextInt();
System.out.println("Enter the number of columns for both matrix:\t");
col = sc.nextInt();
int mat1[][] = new int[row][col];
int mat2[][] = new int[row][col];
int mat3[][] = new int[row][col];
System.out.printf("Enter %d elements for matrix 1\n", row * col);
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
mat1[i][j] = sc.nextInt();
}
}
System.out.printf("Enter %d elements for matrix 2\n", row * col);
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
mat2[i][j] = sc.nextInt();
}
}
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
mat3[i][j] = mat1[i][j] - mat2[i][j];
}
}
System.out.println("The Subtract of two Matrices is:\n");
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
System.out.printf("%d\t", mat3[i][j]);
}
System.out.println("\n");
}
}
}
This program subtracts two matrices of the same dimensions and displays the result. Below is a step-by-step explanation:
1. User Input for Matrix Dimensions
- The program prompts the user to enter:
- The number of rows (
row
). - The number of columns (
col
).
- The number of rows (
- Both matrices must have the same dimensions.
2. Matrix Declaration
- Three 2D arrays are declared:
mat1[][]
→ Stores the first matrix.mat2[][]
→ Stores the second matrix.mat3[][]
→ Stores the resultant matrix (subtraction result).
3. Taking Input for Both Matrices
- The user is prompted to enter elements for both matrices.
- Nested loops are used to iterate through the rows (
i
) and columns (j
) of the matrices.
4. Matrix Subtraction Logic
Each element of mat3[][]
is calculated as:
[ mat3[i][j] = mat1[i][j] - mat2[i][j] ]
- The program iterates through each element using nested loops.
- It subtracts corresponding elements of
mat1[][]
andmat2[][]
and stores the result inmat3[][]
.
5. Displaying the Resultant Matrix
- The final subtracted matrix (
mat3[][]
) is printed in a formatted manner usingSystem.out.printf()
.
Example Execution
Input
Enter the number of rows for both matrices: 2
Enter the number of columns for both matrices: 3
Enter 6 elements for matrix 1:
5 8 3
2 7 6
Enter 6 elements for matrix 2:
1 4 2
3 5 4
Matrix Subtraction
The Subtract of two Matrices is:
4 4 1
-1 2 2
Key Points
- Handles matrices of any valid dimensions
- Ensures both matrices have the same dimensions
- Uses nested loops for input, processing, and output
- Displays formatted output for readability
Output
$ javac SubtractMatrix.java
$ java SubtractMatrix
Enter the number of rows for both matrix:
3
Enter the number of columns for both matrix:
3
Enter 9 elements for matrix 1
34
22
12
86
74
32
45
65
71
Enter 9 elements for matrix 2
99
15
78
85
36
63
45
58
11
The Subtract of two Matrices is:
-65 7 -66
1 38 -31
0 7 60