Matrix Multiplication in Java

Write a Java program to allow the user to enter the dimensions of two matrices A and B and then fill these matrices with integers. Now multiply these two matrices and store the result in the third matrix C. Display all the three matrices.

import java.util.Scanner;
class Multiplication{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("No. of rows of matrix A: ");
        int r1 = Integer.parseInt(in.nextLine());
        System.out.print("No. of columns of matrix A: ");
        int c1 = Integer.parseInt(in.nextLine());
        System.out.print("No. of rows of matrix B: ");
        int r2 = Integer.parseInt(in.nextLine());
        System.out.print("No. of columns of matrix B: ");
        int c2 = Integer.parseInt(in.nextLine());
        if(c1 != r2){
            System.out.println("Multiplication not possible!");
            return;
        }
        int a[][] = new int[r1][c1];
        int b[][] = new int[r2][c2];
        int c[][] = new int[r1][c2];
        System.out.println("Enter matrix A elements:");
        input(a, r1, c1);
        System.out.println("Enter matrix B elements:");
        input(b, r2, c2);
        System.out.println("Matrix A");
        display(a, r1, c1);
        System.out.println("Matrix B");
        display(b, r2, c2);
        for(int i = 0; i < r1; i++){
            for(int j = 0; j < c2; j++){
                for(int k = 0; k < c1; k++){
                    c[i][j] += a[i][k] * b[k][j];
                }
            }
        }
        System.out.println("Matrix C");
        display(c, r1, c2);
    }
    public static void input(int m[][], int r, int c){
        Scanner in = new Scanner(System.in);
        for(int i = 0; i < r; i++){
            for(int j = 0; j < c; j++){
                m[i][j] = Integer.parseInt(in.nextLine());
            }
        }
    }
    public static void display(int m[][], int r, int c){
        for(int i = 0; i < r; i++){
            for(int j = 0; j < c; j++){
                System.out.print(m[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *