Program opened below. You can scroll through the algorithm, Java code and output.
Program 33
Product of Two Matrices
Question
Accept two square matrices of the same order and display their product.
Algorithm
Step 1: Start the program and read the order n of the two square matrices.
Step 2: Declare matrices A and B and a result matrix C, each of order n.
Step 3: Read every element of matrix A row by row.
Step 4: Read every element of matrix B row by row.
Step 5: Select a row i of matrix A and a column j of matrix B.
Step 6: Set C[i][j] to zero before calculating the product element.
Step 7: Use a third loop with index k to select corresponding elements from the row and column.
Step 8: Multiply A[i][k] by B[k][j] and add the product to C[i][j].
Step 9: Repeat the multiplication and addition for every value of k.
Step 10: Repeat the calculation for every column j in the selected row.
Step 11: Repeat the calculation for all rows i.
Step 12: Display the product matrix with each row on a separate line.
Step 13: Stop the program.
Java program
Javaimport java.util.*;
class MatrixProduct
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter order: ");
int n = sc.nextInt();
int[][] a = new int[n][n];
int[][] b = new int[n][n];
int[][] c = new int[n][n];
System.out.println("Enter matrix A:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
a[i][j] = sc.nextInt();
}
}
System.out.println("Enter matrix B:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
b[i][j] = sc.nextInt();
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
c[i][j] += a[i][k] * b[k][j];
}
}
}
System.out.println("Product matrix:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(c[i][j] + "\t");
}
System.out.println();
}
}
}Sample output
Input: Input: n=2; A: 1 2 / 3 4; B: 1 0 / 0 1
Output: Product matrix: 1 2
3 4