Program for Matrix multiplication in Java.



Note:  Step 1: Make sure that the the number of columns in the 1st one equals the number of rows in the 2nd one. (The pre-requisite to be able to multiply) 

Step 2: Multiply the elements of each row of the first matrix by the elements of each column in the second matrix. 

Step 3: Add the products.


public class MatrixMultiplication {

    public static void main(String args[]) {
        int a[][] = new int[3][3];
        int b[][] = new int[3][3];
        int mul[][] = new int[3][3];
        int sum = 0;
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter element of First Matrix ");
        for (int i = 0; i <= 2; i++) {

            for (int j = 0; j <= 2; j++) {
                a[i][j] = sc.nextInt();

            }
        }
        System.out.println("Value of  Matrix is ");
        for (int i = 0; i <= 2; i++) {

            for (int j = 0; j <= 2; j++) {
                System.out.print(a[i][j] + " ");

            }
            System.out.println();
        }

        System.out.println("Enter element of Second Matrix ");
        for (int i = 0; i <= 2; i++) {

            for (int j = 0; j <= 2; j++) {
                b[i][j] = sc.nextInt();

            }
        }
        System.out.println("Value of Second Matrix is ");
        for (int i = 0; i <= 2; i++) {

            for (int j = 0; j <= 2; j++) {
                System.out.print(b[i][j] + " ");

            }
            System.out.println();
        }

        //Logic for matrix multiplication

        for (int k = 0; k < 3; k++) 
        {
            for (int i = 0; i < 3; i++) 
            {
                for (int j = 0; j < 3; j++) 
                {
                    sum=sum+(a[k][j]*b[j][i]);
                }
                mul[k][i]=sum;
                sum=0;
            }
        }
        
        System.out.println("Multiplication of both Matrix is ");
        for (int i = 0; i <= 2; i++) {

            for (int j = 0; j <= 2; j++) {
                System.out.print(mul[i][j] + " ");

            }
            System.out.println();
        }

    }

}

Output:

Enter element of First Matrix 
1
2
3
4
5
6
7
8
9

Value of  Matrix is 
1 2 3 
4 5 6 
7 8 9 

Enter element of Second Matrix 
1
2
3
4
5
6
7
8
9

Value of Second Matrix is 
1 2 3 
4 5 6 
7 8 9 

Multiplication of both Matrix is 
30 36 42 
66 81 96 
102 126 150 







No comments:

Post a Comment