KnowledgeBoat Logo

Computer Science

Write a program in Java to store the elements in two different double dimensional arrays (in matrix form) A and B each of order 4 x 4. Find the product of both the matrices and store the result in matrix C. Display the elements of matrix C.

Note:
Two matrixes can be multiplied only if the number of columns of the first matrix must be equal to the number of rows of the second matrix.

Sample Input: Matrix A

3212
6450
7-102
4311

Sample Input: Matrix B

-2-4-10
36-52
5346
0-225

Sample Output: Matrix C

5-1-520
2515-638
-17-382-8
63-1317

Java

Java Arrays

16 Likes

Answer

import java.util.Scanner;

public class KboatDDAMultiply
{
    public static void main(String args[]) {

        Scanner in = new Scanner(System.in);

        int a[][] = new int[4][4];
        int b[][] = new int[4][4];
        int c[][] = new int[4][4];

        System.out.println("Enter elements of Matrix A");
        for (int i = 0; i < 4; i++) {
            System.out.println("Enter Row "+ (i+1) + " :");
            for (int j = 0; j < 4; j++) {
                a[i][j] = in.nextInt();
            }
        }

        System.out.println("Enter elements of Matrix B");
        for (int i = 0; i < 4; i++) {
            System.out.println("Enter Row "+ (i+1) + " :");
            for (int j = 0; j < 4; j++) {
                b[i][j] = in.nextInt();
            }
        }
        
        System.out.println("Input Matrix A:");
        printMatrix(a, 4, 4);
        
        System.out.println("Input Matrix B:");
        printMatrix(b, 4, 4);

        //Multiply the Matrices
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                for (int k = 0; k < 4; k++) {
                    c[i][j] += a[i][k] * b[k][j];
                }
                
            }
        }
        
        System.out.println("Output Matrix C:");
        printMatrix(c, 4, 4);
    }
    
    public static void printMatrix(int arr[][], int m, int n) {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

Output

BlueJ output of Write a program in Java to store the elements in two different double dimensional arrays (in matrix form) A and B each of order 4 x 4. Find the product of both the matrices and store the result in matrix C. Display the elements of matrix C. Note: Two matrixes can be multiplied only if the number of columns of the first matrix must be equal to the number of rows of the second matrix. Sample Input: Matrix A Sample Input: Matrix B Sample Output: Matrix C

Answered By

6 Likes


Related Questions