MULTIPLY TWO MATRIX

This is the program by using the for loopwe can find out the multiplication of two matrices.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.Scanner;
public class MulMatrix
{
     public static void main(String args[])
     {
          int m, n, p, q, sum = 0, i, j, k;
          Scanner in = new Scanner(System.in);
          System.out.println("Enter the number of rows and columns of  matrix");
          m = in.nextInt();
          n = in.nextInt();
          int first[][] = new int[m][n];
          System.out.println("Enter the elements of first matrix");
          for ( i = 0 ; i < m ; i++ )
          for ( j = 0 ; j < n ; j++ )
          first[i][j] = in.nextInt();
          System.out.println("Enter the number of rows and columns of  matrix");
          p = in.nextInt();
          q = in.nextInt();
          if ( n != p )
          System.out.println("Matrices with entered orders can't be multiplied with each other.");
          else
          {
                int second[][] = new int[p][q];
                int multiply[][] = new int[m][q];
                System.out.println("Enter the elements of second matrix");
                for ( i= 0 ; i < p ; i++ )
                for ( j = 0 ; j < q ; j++ )
                second[i][j] = in.nextInt();
                for ( i = 0 ; i < m ; i++ )
                {
                    for ( j = 0 ; j < q ; j++ )
                    {  
                        for ( k = 0 ; k < p ; k++ )
                        {
                            sum = sum + first[i][k]*second[k][j];
                        }  
                        multiply[i][j] = sum;
                        sum = 0; 
                    }
                }
                System.out.println("Product of entered matrices:-");
                for ( i = 0 ; i < m ; i++ )         
                for ( j = 0 ; j < q ; j++ )
                System.out.print(multiply[i][j]+"\t");
            }
    }

 

Output:Multiply two Matrices
gcdn