MatrixMultiplication.java
62 linesjava
DOWNLOAD
1// Aim: Program to perform Matrix Multiplication.
2import java.util.Scanner;
3public class MatrixMultiplication {
4    public static void main(String[] args) {
5        Scanner sc = new Scanner(System.in);
6        System.out.print("Enter the number of rows of the first matrix: ");
7        int r1 = sc.nextInt();
8        System.out.print("Enter the number of columns of the first matrix: ");
9        int c1 = sc.nextInt();
10        System.out.print("Enter the number of rows of the second matrix: ");
11        int r2 = sc.nextInt();
12        System.out.print("Enter the number of columns of the second matrix: ");
13        int c2 = sc.nextInt();
14        if(c1!=r2)
15        {
16            System.out.println("The matrices cannot be multiplied with each other.");
17        }
18        else
19        {
20            int a[][] = new int[r1][c1];
21            int b[][] = new int[r2][c2];
22            int mul[][] = new int[r1][c2];
23            System.out.println("Enter the elements of the first matrix: ");
24            for(int i=0;i<r1;i++)
25            {
26                for(int j=0;j<c1;j++)
27                {
28                    a[i][j] = sc.nextInt();
29                }
30            }
31            System.out.println("Enter the elements of the second matrix: ");
32            for(int i=0;i<r2;i++)
33            {
34                for(int j=0;j<c2;j++)
35                {
36                    b[i][j] = sc.nextInt();
37                }
38            }
39            for(int i=0;i<r1;i++)
40            {
41                for(int j=0;j<c2;j++)
42                {
43                    for(int k=0;k<c1;k++)
44                    {
45                        mul[i][j] += a[i][k]*b[k][j];
46                    }
47                }
48            }
49            System.out.println("The product of the two matrices is: ");
50            for(int i=0;i<r1;i++)
51            {
52                for(int j=0;j<c2;j++)
53                {
54                    System.out.print(mul[i][j]+" ");
55                }
56                System.out.println();
57            }
58        }
59        sc.close();
60    }
61}
62