In: Computer Science
To understand the value of counting loops:
Sample Result is shown below:
Enter the number of rows of matrix A: 2
Enter the number of columns of matrix A: 3
Enter the number of columns of matrix B: 3
Enter the number of columns of matrix B: 4
Enter matrix A;
1 2 3
4 5 6
Enter matrix B:
7 8 9 10
11 12 13 14
15 16 17 18
Matrix A:
1 2 3
4 5 6
Matrix B:
7 8 9 10
11 12 13 14
15 16 17 18
Product of matrix A and Matrix B ( A x B) :
74 80 86 92
173 188 203 218
Program:
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
int rowSizeA,columnSizeA,rowSizeB,columnSizeB;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows of matrix A: ");
rowSizeA = sc.nextInt();
System.out.print("Enter the number of columns of matrix A: ");
columnSizeA = sc.nextInt();
System.out.print("Enter the number of rows of matrix B: ");
rowSizeB = sc.nextInt();
System.out.print("Enter the number of columns of matrix B: ");
columnSizeB = sc.nextInt();
int A[][] = new int[rowSizeA][columnSizeA];
int B[][] = new int[rowSizeB][columnSizeB];
if (columnSizeA != rowSizeB){
System.out.println("The matrices can't be multiplied with each other.");
System.exit(0);
}
System.out.println("Enter matrix A:");
for (int i = 0; i < rowSizeA; i++)
{
for (int j = 0; j < columnSizeA; j++)
{
A[i][j] = sc.nextInt();
}
}
System.out.println("Enter matrix B:");
for (int i = 0; i < rowSizeB; i++)
{
for (int j = 0; j < columnSizeB; j++)
{
B[i][j] = sc.nextInt();
}
}
int C[][] = new int[rowSizeA][columnSizeB];
for (int i = 0; i < rowSizeA; i++)
{
for (int j = 0; j < columnSizeB; j++)
{
for (int k = 0; k < rowSizeB; k++)
{
C[i][j] = C[i][j] + A[i][k] * B[k][j];
}
}
}
System.out.println("Matrix A:");
for (int i = 0; i < rowSizeA; i++)
{
for (int j = 0; j < columnSizeA; j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}
System.out.println("Matrix B:");
for (int i = 0; i < rowSizeB; i++)
{
for (int j = 0; j < columnSizeB; j++)
{
System.out.print(B[i][j]+"\t");
}
System.out.println();
}
System.out.println("Product of matrix A and Matrix B ( A x B) : ");
for (int i = 0; i < rowSizeA; i++)
{
for (int j = 0; j < columnSizeB; j++)
System.out.print(C[i][j]+"\t");
System.out.print("\n");
}
}
}
Output: