trickbd

Java program source code for multiplying 2 Matrix

import java.util.*;

class matrix
{
static Scanner input=new Scanner(System.in);
public static void main(String[] args)
{

//starting matrix programm…
//a matrix example
//a=|2 3| b=|5 6|
// |7 8| |3 2|

//result |2*5+3*3 2*6+3*2|
// |7*5+8*3 7*6+8*2|

//now we need to first input value of row and column
//we need to define row as r and collum as c

//we r now trying to take input by using foor loop
int r,c,k,addMatrix=0;
int ar,ac;

System.out.println(“Please input the row number of matrix a”);
ar=input.nextInt();
System.out.println(“Please input the colum number of matrix a”);
ac=input.nextInt();

int br,bc;

System.out.println(“Please input the row number of matrix b”);
br=input.nextInt();
System.out.println(“Please input the column number of matrix a”);
bc=input.nextInt();

int[][] a=new int[ar][ac];
int[][] b=new int[br][bc];
int[][] result=new int[ar][bc];

while(ac!=br){
System.out.println(“First matrix column and second matrix row need to be eqaul”);
//again taking input from user
System.out.println(“Please input the row number of matrix a again”);
ar=input.nextInt();
System.out.println(“Please input the colum number of matrix a again”);
ac=input.nextInt();

System.out.println(“Please input the row number of matrix b again”);
br=input.nextInt();
System.out.println(“Please input the column number of matrix a again”);
bc=input.nextInt();
}

if(ac==br){
//Input value of “a” matrix
System.out.println(“I nput value of a … u need to input value of 1st row first then second row”);
for(r=0;r<ar;r++){
for(c=0;c<ac;c++){
a[r][c]=input.nextInt();
}
}

for (r = 0; r < ar; r++) {
for (c = 0; c < ac; c++) {

System.out.print(a[r][c]+”\t”);
}
System.out.println(“\n”);
}
//input value of “b” matrix
System.out.println(“I nput value of b … u need to input value of row first”);

for(r=0;r<br;r++){
for(c=0;c<bc;c++){
b[r][c]=input.nextInt();
}
}

for (r = 0; r <br; r++) {

for (c = 0; c <bc; c++) {
System.out.print(b[r][c]+”\t”);
}
System.out.println(“\n”);
}

//multiplication value of matrix
for (r = 0; r <ar; r++) {
for (c = 0; c <bc; c++) {
for (k = 0; k <br; k++) {
addMatrix=addMatrix+a[r][k]*b[k][c];
} //end of k loop
result[r][c]=addMatrix;
addMatrix=0;
}
}

for (r = 0; r < ar; r++) {
for (c = 0; c <bc; c++) {
System.out.print(result[r][c]+”\t”);
}
System.out.println(“\n”);
}

}
}
}

 
You can only multiply 2 matrix by using this program 🙂
[As this is only source code of the pprogram you need a java compiler to run this program 🙂 ]