Code:
public static void main(String[] args) {
int m, n, p, q, c, d, k;
int sum1 = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the number of rows and columns for the first matrix.");
m = scan.nextInt();
n = scan.nextInt();
int first[][] = new int[m][n];
System.out.println("Enter the elements of first matrix:");
for ( c = 0 ; c < m ; c++ ) // The numbers are put into the matrix.
for ( d = 0 ; d < n ; d++ )
first[c][d] = scan.nextInt();
System.out.println("Please enter the number of rows and columns for the second matrix.");
p = scan.nextInt();
q = scan.nextInt();
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
int sum[][] = new int[m][n];
System.out.println("Enter the elements of second matrix:");
for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
second[c][d] = scan.nextInt();
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum1 = sum1 + first[c][k]*second[k][d];
}
multiply[c][d] = sum1;
sum1 = 0;
}
}
System.out.println("The product of the two matrices is: ");
for ( c = 0 ; c < m ; c++ ) {
for ( d = 0 ; d < q ; d++ ) {
System.out.print(multiply[c][d]+"\t");
}
System.out.print("\n");
}
for ( c = 0 ; c < m ; c++ ) {
for ( d = 0 ; d < n ; d++ ) {
sum[c][d] = first[c][d] + second[c][d];
System.out.println("The sum of the two matrices is: ");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
System.out.print(sum[c][d]+"\t");
System.out.println();
}
}
}
}
}
The Output is incorrect for the sum. It prints like this:
The sum of the two matrices is:
0 0
0 0
Anyone know how to fix this?
I've been trying to figure this out, but ended up getting more errors. Sorry for all the questions, I'm a beginner. Thank you :)