Matrix Multiplication in Java
Write a Java program to perform matrix multiplication.
Multiplication of two matrices is possible only if number of columns in matrix A = number of rows in matrix B.
The dimensions of the resulting matrix will be:
Number of rows of matrix A × Number of columns of matrix B.
import java.util.Scanner;
class Multiply{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Rows of matrix 1: ");
int r1 = Integer.parseInt(in.nextLine());
System.out.print("Columns of matrix 1: ");
int c1 = Integer.parseInt(in.nextLine());
System.out.print("Rows of matrix 2: ");
int r2 = Integer.parseInt(in.nextLine());
System.out.print("Columns of matrix 2: ");
int c2 = Integer.parseInt(in.nextLine());
if(c1 != r2){
System.out.println("Can't multiply!");
return;
}
int a[][] = new int[r1][c1];
int b[][] = new int[r2][c2];
int c[][] = new int[r1][c2];
System.out.println("Enter matrix 1 elements:");
for(int i = 0; i < r1; i++){
for(int j = 0; j < c1; j++){
a[i][j] = Integer.parseInt(in.nextLine());
}
}
System.out.println("Enter matrix 2 elements:");
for(int i = 0; i < r2; i++){
for(int j = 0; j < c2; j++){
b[i][j] = Integer.parseInt(in.nextLine());
}
}
for(int i = 0; i < r1; i++){
for(int j = 0; j < c2; j++){
for(int k = 0; k < c1; k++){
c[i][j] += a[i][k] * b[k][j];
}
}
}
System.out.println("Product:");
for(int i = 0; i < r1; i++){
for(int j = 0; j < c2; j++){
System.out.print(c[i][j] + "\t");
}
System.out.println();
}
}
}
class Multiply{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Rows of matrix 1: ");
int r1 = Integer.parseInt(in.nextLine());
System.out.print("Columns of matrix 1: ");
int c1 = Integer.parseInt(in.nextLine());
System.out.print("Rows of matrix 2: ");
int r2 = Integer.parseInt(in.nextLine());
System.out.print("Columns of matrix 2: ");
int c2 = Integer.parseInt(in.nextLine());
if(c1 != r2){
System.out.println("Can't multiply!");
return;
}
int a[][] = new int[r1][c1];
int b[][] = new int[r2][c2];
int c[][] = new int[r1][c2];
System.out.println("Enter matrix 1 elements:");
for(int i = 0; i < r1; i++){
for(int j = 0; j < c1; j++){
a[i][j] = Integer.parseInt(in.nextLine());
}
}
System.out.println("Enter matrix 2 elements:");
for(int i = 0; i < r2; i++){
for(int j = 0; j < c2; j++){
b[i][j] = Integer.parseInt(in.nextLine());
}
}
for(int i = 0; i < r1; i++){
for(int j = 0; j < c2; j++){
for(int k = 0; k < c1; k++){
c[i][j] += a[i][k] * b[k][j];
}
}
}
System.out.println("Product:");
for(int i = 0; i < r1; i++){
for(int j = 0; j < c2; j++){
System.out.print(c[i][j] + "\t");
}
System.out.println();
}
}
}
Comments
Post a Comment