How to do subtraction of Matrix in java

Subtraction of Matrix




Steps to do this:-
1. take i,j integers (i,j is for loop)
2.take 
int a[][]=new int[3][3] (for 1st matrix)
int a[][]=new int[3][3] (for 2nd matrix)
 int a[][]=new int[3][3] (for the result matrix)

 3. take a Scanner class

 4. now start the i loop (i=0;i<3;i++) and start the j loop (j=0;j<3;j++) inside the i loop now take the first matrix value from user and also take 2nd matrix value

5.now do the calculation 
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)

{
c[i][j]=a[i][j]-b[i][j]

}
}
and for printing the value print inside the j loop and print a new line outside of the  j loop

5.save and run


The Source code

import java.util.Scanner;
class sub
{
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        int i,j;//for loop
        int a[][]=new int[3][3];// first matrix
        int b[][]=new int[3][3];//2nd matrix
        int c[][]=new int[3][3];//for the result matrix
        System.out.println("enter the first matrix:");
        for(i=0;i<3;i++)
        {
            for(j=0;j<3;j++)
            {
                a[i][j]=s.nextInt();
            }
        }
        System.out.println("enter the 2nd matrix");
        for(i=0;i<3;i++)
        {
            for(j=0;j<3;j++)
            {
                b[i][j]=s.nextInt();
            }
        }

        //the calculation
        for(i=0;i<3;i++)
        {
            for(j=0;j<3;j++)
            {
                c[i][j]=a[i][j]-b[i][j];
            }
        }
        System.out.println("the ans is:");
        for(i=0;i<3;i++)
        {
            for(j=0;j<3;j++)
            {
                System.out.print(c[i][j]+" ");
            }
            System.out.println();//for the new line
        }

    }
}

OUTPUT



Watch My Video

          

Comments

Popular Posts