Matrics subtracton in JAVA programming


import java.util.Scanner;

public class MatrixSub {

    public static void main(String[] args) {
        Scanner myScanner=new Scanner(System.in);
        int m,n,p,q;
       
        System.out.print("Enter first matrics row & column : ");
        m=myScanner.nextInt();
        n=myScanner.nextInt();
        int[][] first=new int[m][n];
        System.out.print("Enter second matrics row & column : ");
        p=myScanner.nextInt();
        q=myScanner.nextInt();
        if((m!=p)||(n!=q)){
            System.out.println("Substraction not Possible");
        }else{
        int[][] second=new int[p][q];
        System.out.println("Enter firast Matrics : ");
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                first[i][j]=myScanner.nextInt();
            }
        }
        System.out.println("Enter second Matrics : ");
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                second[i][j]=myScanner.nextInt();
            }
        }
        int[][] result=new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                result[i][j]=first[i][j]-second[i][j];
            }
        }
        System.out.println("Substraction of the two matrics is : ");
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(result[i][j]+"\t");
            }
            System.out.println();
        }
        }
    }

}

//Enter first matrics row & column : 2 2
//Enter second matrics row & column : 2 2
//Enter firast Matrics :
//2 3 4 5
//Enter second Matrics :
//6 7 8 9
//Substraction of the two matrics is :
//-4    -4   
//-4    -4   

No comments:

Post a Comment