Matrix Multiplication Using Arrays And Loops in Java
Do Matrix Multiplication in Java by the help of Arrays and Loops
Answer:
I used Vs Code as IDE, you can also use Eclipse and run the code in your computer. The result Image shown at the bottom. I used 2x2 matrix, you can also use for big matrixes, and remember that first matrix column must be equal with the rows of second matrix.
import java.util.Scanner;
public class Ques4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter Dimension");
System.out.println("In Matrix multiplication rows and columns must be same!");
int rows = sc.nextInt();
int cols = sc.nextInt();
int a[][] = new int[rows][cols];
int b[][] = new int[rows][cols];
System.out.println("Enter array A");
for(int i = 0; i< rows; i++){
for(int j = 0; j< cols; j++){
a[i][j] = sc.nextInt();
}
}
System.out.println("Enter array B");
for(int i = 0; i< rows; i++){
for(int j = 0; j< cols; j++){
b[i][j] = sc.nextInt();
}
}
int c[][] = new int[rows][cols];
for(int i = 0; i<rows; i++){
for(int j = 0; j<cols; j++){
c[i][j] = a[i][j] * b[j][i] + a[i][j] * b[j][i];
}
}
System.out.println("Matrix multiplication result C is");
System.out.println("Result array C");
for(int i = 0; i< rows; i++){
for(int j = 0; j< cols; j++){
System.out.print(c[i][j] + " ");
}
System.out.println();
}
sc.close();
}
}
Comments
Post a Comment