Program opened below. You can scroll through the algorithm, Java code and output.

Product of Two Matrices

Download .java

Question

Accept two square matrices of the same order and display their product.

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
import 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();
        }
    }
}
Input: Input: n=2; A: 1 2 / 3 4; B: 1 0 / 0 1 Output: Product matrix: 1 2 3 4
← Previous Program 33 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.