Matrix subtraction in Java

Source code :

public class Java
{
   public static void main(String args[])
   {
       int i, j;
       int mat1[][] = new int[2][2];
       int mat2[][] = new int[2][2];
       int mat3[][] = new int[2][2];
	   
        mat1[0][0]=10;  
        mat1[0][1]=2;  
        mat1[1][0]=3;  
        mat1[1][1]=4;  
      
        mat2[0][0]=2;  
        mat2[0][1]=3;  
        mat2[1][0]=4; 
        mat2[1][1]=5; 
       
	   
       System.out.print("Subtracting Matrices (i.e. Matrix1 - Matrix2)...\n");
       for(i=0; i<2; i++)
       {
           for(j=0; j<2; j++)
           {
               mat3[i][j] = mat1[i][j] - mat2[i][j];
           }
       }
	   
       System.out.print("Result of Matrix1 - Matrix2 is :\n");
       for(i=0; i<2; i++)
       {
           for(j=0; j<2; j++)
           {
               System.out.print(mat3[i][j]+ " ");
           }
           System.out.println();
       }
   }
}

Output :

Result of Matrix 1 - Matrix 2 is :
8 -1
-1 -1 

Algorithm :

  1. Initialize the variables as i and j
  2. Enter the values of matrix 1 and matrix 2 in the program
  3. Use the formula for subtract the matrices
  4. Compile the java program
  5. Execute the file

Output :


                

Comments :