Need help writing a java program Write a program that allows

Need help writing a java program.

Write a program that allows the user to enter two matrices. First ask the user of the dimensions of both matrices. Then verify, based on the two matrices, which operations on matrices are possible (multiplication, addition, subtraction). Use two dimensional arrays for this exercise. Output the solution in the following form: (Example of a 4 times 4 matrix multiplied with a 4 times 2 matrix)

Solution

import java.util.Scanner;

class MatrixOperations
{
public static void main(String args[])
{
int rows1,cols1, rows2,cols2,sum = 0, i, j, k;

Scanner scan = new Scanner(System.in);
System.out.println(\"Enter the number of rows and columns of first matrix\");
rows1 = scan.nextInt();
cols1 = scan.nextInt();

int first[][] = new int[rows1][cols1];

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

for ( i = 0 ; i < rows1 ; i++ )
for ( j = 0 ; j < cols1 ; j++ )
first[i][j] = scan.nextInt();

System.out.println(\"Enter the number of rows and columns of second matrix\");
rows2 = scan.nextInt();
cols2 = scan.nextInt();

if(rows1 == rows2 && cols1 == cols2) //check the orders of matrices
System.out.println(\"Matrices can be added or subtracted\");
else
System.out.println(\"Matrices can not be added or subtracted\");
if ( cols1 != rows2 )
System.out.println(\"Matrices can not be multiplied with each other.\");
else
{
int second[][] = new int[rows2][cols2];
int multiply[][] = new int[rows1][cols2];

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

for ( i = 0 ; i < rows2 ; i++ )
for ( j = 0 ; j < cols2 ; j++ )
second[i][j] = scan.nextInt();

for ( i = 0 ; i < rows1 ; i++ )
{
for ( j = 0 ; j < cols2 ; j++ )
{   
for ( k = 0 ; k < rows2 ; k++ )
{
sum = sum + first[i][k]*second[k][j];
}

multiply[i][j] = sum;
sum = 0;
}
}

System.out.println(\"Product of matrices:-\");

for ( i = 0 ; i < rows1 ; i++ )
{
for ( j = 0 ; j < cols2 ; j++ )
System.out.print(multiply[i][j]+\"\\t\");

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

output:

Need help writing a java program. Write a program that allows the user to enter two matrices. First ask the user of the dimensions of both matrices. Then verify
Need help writing a java program. Write a program that allows the user to enter two matrices. First ask the user of the dimensions of both matrices. Then verify

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site