 Last Updated:

# Matrix Multiplication ## Algorithm

Input: Input rows and column of the first and second matrices, elements of the matrices
output: Displays the multiplication of element of the matrices

1. Start
2. Input the number of row and column of 1st matrix and store it in m1, n1
3. Input the number of row and column of 2nt matrix and store it in m2, n2
4. if n1 != m2
4.1 Print "Matrix multiplication not possible"
5. else
5.1 Input the elements of matrix 1 and matrix 2 say a [m1] [n1] and b [m2] [n2]
5.2 Print "The multiplication of matrix 1 and 2 is "
5.3 for i = 0 to m1
5.3.1 for j = 0 to n2
5.3.1.1 c [ i ] [ j ] = 0
5.3.1.2 for k = 0 to n1
5.3.1.2.1 c [ i ] [ j ] = c [ i ] [ j ] + a [ i ] [ k ] * b [ k ] [ j ]
6. print the matrix c
7. Stop

## Java Program import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int m1,n1,m2,n2;
System.out.printf("Enter the number of rows of first matrix:");
System.out.printf("Enter the number of coloumns of first matrix:");
System.out.printf("Enter the number of rows of second matrix:");
System.out.printf("Enter the number of coloumns of second matrix:");
int a[ ] [ ] = new int [m1] [n1];
int b[ ] [ ] = new int [m2] [n2];
int c[ ] [ ] = new int [m1] [n2];
if(n1!=m2) {
System.out.printf("Matrix multiplication not possible");
}
else {
System.out.println("Enter the elements of first matrix:");
for(int i=0;i<m1;i++) {
for(int j=0;j<n1;j++) {
a [ i ] [ j ] = reader.nextInt( );
}
}
System.out.println("Enter the elements of second matrix:");
for(int i=0;i<m2;i++) {
for(int j=0;j<n2;j++) {
b [ i ] [ j ] = reader.nextInt( );
}
}
for(int i=0;i<m1;i++) {
for(int j=0;j<n2;j++) {
c [ i ] [ j ] = 0;
for(int k=0;k<n1;k++) {
c [ i ] [ j ] = c [ i ] [ j ] + ( a [ i ] [ k ] * b [ k ] [ j ] );
}
}
}
System.out.println("The multiplied matrix is:");
for(int i=0;i<m1;i++) {
for(int j=0;j<n2;j++) {
System.out.printf(c [ i ] [ j ] + "\t");
}
System.out.println();
}
}
}
}

## Output

Enter the number of rows of the first matrix: 2
Enter the number of columns of the first matrix: 2
Enter the number of rows of  the second matrix: 2
Enter the number of columns of the second matrix: 2
Enter the elements of the first matrix:
1
2
3
4
Enter the elements of the second matrix:
1
2
3
4
The matrix multiplication is

7       22
7       22