# What's wrong with the code? Multiplication of Matrices

• November 4th, 2013, 10:09 AM
ksheth94
What's wrong with the code? Multiplication of Matrices
I ALWAYS GET THE OUTPUT AS ZERO. PLEASE TELL ME WHERE IS MY MISTAKE
import java.util.*;
class Multi
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int m1,n1,m2,n2,i,j,k;

System.out.println("Enter the no of rows for first matrix");
m1=sc.nextInt();
System.out.println("Enter the no of coloumns for first matrix");
n1=sc.nextInt();
System.out.println("Enter the no of rows for second matrix");
m2=sc.nextInt();
System.out.println("Enter the no of coloumns for second matrix");
n2=sc.nextInt();
int a[][]=new int[m1][n1];
int b[][]=new int[m2][n2];
int c[][]=new int[m1][n2];
if(n1!=m2)
System.out.println("Not possible");
else
{
System.out.println("Enter the elements of first matrix");
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
{
a[i][j]=sc.nextInt();

}
}
System.out.println("Enter the elements of second matrix");
for(i=0;i<m2;i++)
{
for(j=0;j<n2;j++)
{
a[i][j]=sc.nextInt();
}
}
for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
{
c[i][j]=0;
{
for(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(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
{
System.out.print(c[i][j]+"\t");
}
System.out.println();
}
}

}
}
• November 4th, 2013, 11:29 AM
copeg
Re: What's wrong with the code? Multiplication of Matrices
First, please read the announcements at to the of every subforum. This post describes how to wrap your code in the code tags (as is, your code is virtually unreadable). Next, add some println's to evaluate the values of each entered matrix (hint, esp. the b array)
• November 4th, 2013, 11:33 AM
Norm
Re: What's wrong with the code? Multiplication of Matrices
The Arrays class has a method: deepToString() that is useful when debugging two dim arrays.
Use it to format the array for printing.