AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



corejava-array: How to calculate the product of two matrices in java?

write a java program to output product of two matrices.

corejava x 353
array x 12
Posted On : 2014-06-09 06:36:48.0
profile prince haxor - anyforum.in prince haxor
1930
up-rate
4
down-rate

Answers


Following is working java code using scanner class to find the product of two matrices. Keep in mind a rule that is only those matrices can be multiplied in which the number of columns of first matrix should be equal to the number of rows of second matrix. If your first matrix is of dimension m x n and second matrix is of dimension p x q, then to multiply these matrices n==p should be true.


******************* Java program to find the multiply/product of two matrices ******************

MatricesMultiplication.java:
----------------------------------------


import java.util.Scanner;

class MatricesMultiplication
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;

Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of first matrix separated by white space:");
m = in.nextInt();
n = in.nextInt();

int first[][] = new int[m][n];

System.out.println("Enter the elements of first matrix in the matrix form");

for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
first[c][d] = in.nextInt();

System.out.println("Enter the number of rows and columns of second matrix separated by white space");
p = in.nextInt();
q = in.nextInt();

if ( n != p )
System.out.println("Sorry! Matrices with entered orders can not be multiplied with each other.");
else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];

System.out.println("Enter the elements of second matrix in the matrix form");

for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
second[c][d] = in.nextInt();

for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}

multiply[c][d] = sum;
sum = 0;
}
}

System.out.println("Following is the product of given metrices.....");

for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
System.out.print(multiply[c][d]+"\t");

System.out.print("\n");
}
}
}
}

/***************************************** Output ***************************************/
product of two matrices in java-AnyForum

Posted On : 2014-06-09 16:06:32
Satisfied : 2 Yes  0 No
profile Garima Gupta - anyforum.in Garima Gupta
596129558962
Reply This Thread
up-rate
5
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in