Write a Java program to multiply two given matrices.

//Program to find matrix multiplication
import java.util.*;
class Matrixmul
{
            public static void main(String args[])
            {
                        Scanner scr=new Scanner(System.in);
                        int m,n,p,q;
                        System.out.println(“nEnter the order of the Matrix A: “);
                        m=scr.nextInt();
                        n=scr.nextInt();
                        int a[][]=new int[m][n];
                        System.out.println(“nEnter the order of Matrix B:  “);
                        p=scr.nextInt();
                        q=scr.nextInt();
                        int b[][]=new int[p][q];
                        int c[][]=new int[m][q];
                        if(n==p)
                        {
                                    System.out.println(“nEnter elements into matrix A “);
                                    for(int i=0;i<m;i++)
                                    for(int j=0;j<n;j++)
                                    a[i][j]=scr.nextInt();
                                    System.out.println(“nEnter elements into matrix B “);
                                    for(int i=0;i<p;i++)
                                    for(int j=0;j<q;j++)
                                    b[i][j]=scr.nextInt();
                                    for(int i=0;i<m;i++)
                                    for(int j=0;j<q;j++)
                                    {
                                                c[i][j]=0;
                                                for(int k=0;k<n;k++)
                                                c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
                                    }
                                   
System.out.println(“nAfter Multiplication resultent matrix is :”);
                                    for(int i=0;i<n;i++)
                                    {         
                                                for(int j=0;j<q;j++)
                                                System.out.print(c[i][j]+”  “);
                                                System.out.println(“n”);
                                   
                                    }
                        }
                        else
                        System.out.println(“nMatrix multiplication is not possible with given order”);
            }
}
Output:
Enter the order of the Matrix A:
2
2
Enter the order of Matrix B:
2
2
Enter elements into matrix A
1 0 0 1
Enter elements into matrix B
1 2 3 4
After Multiplication resultant matrix is :
1  2

3  4

Leave a Reply

Your email address will not be published. Required fields are marked *

Enable Notifications OK No thanks