This site "java learning concept" is very useful for programming languages like JAVA,PYTHON,C,C++, Data Structures etc.Java learning Concept also provides technical materials , which are related to latest technologies. We provides very easy lectures to our viewers from beginning to advance level.We focus logical content instead of theoretical content.Our coding lecture are just fun and hope you will enjoy.

Wednesday, 23 October 2019

Matrix Multiplication In java

How To Multiply Two Matrix in java:

Today we gonna discuss very important program in java ,which is frequently asked in almost all coding interviews named with matrix multiplication. We will focus on the programming logic instead of a theory ,So let's get started.
Example:


import java.util.Scanner;
class MultiplicationMatrix
{
public static void main(String[] args)
{
int sum=0;

System.out.println("Enter rows");
Scanner sc=new Scanner(System.in);
int rows=sc.nextInt();
System.out.println("Enter colums");
int cols=sc.nextInt();
int[][] a=new int[rows][cols];
int[][] b=new int[rows][cols];
int[][] multi=new int[rows][cols];
System.out.println("Enter array-1 data");
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
System.out.println("array-1["+i+"]["+j+"]");
a[i][j]=sc.nextInt();

}

System.out.println("");
}


System.out.println("Enter array-2 data");
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
System.out.println("array-2["+i+"]["+j+"]");
b[i][j]=sc.nextInt();

}

System.out.println("");
}



System.out.println("print array-1 data");
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
System.out.print(a[i][j]+"\t");


}

System.out.println("");
}


System.out.println("print array-2 data");
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
System.out.print(b[i][j]+"\t");


}

System.out.println("");
}

System.out.println("print multipication of array ");
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
for(int k=0;k<2;k++)
{
multi[i][j]=multi[i][j]+a[i][k]*b[k][j];

}

System.out.print(multi[i][j]+"\t");


}

System.out.println("");
}

}
}
Output:

Enter rows
2
Enter columns
2
Enter array-1 data
array-1[0][0]
3
array-1[0][1]
4

array-1[1][0]
1
array-1[1][1]
4

Enter array-2 data
array-2[0][0]
5
array-2[0][1]
1

array-2[1][0]
4
array-2[1][1]
3

print array-1 data
3       4
1       4
print array-2 data
5       1
4       3
multiplication of array
31      15

21      13




                                  

No comments:

Post a Comment

Adbox