28 August 2018

Java Program to multiply two matrices

 //Program to multiply two matrices
import java.util.*;
class matrixmul
    {
  public static void main(String args[] )
      { 
         int m,n,p,q,i,j,k;
         int [][]a =new int[10][10];
         int [][]b=new int[10][10];
         int [][]c=new int[10][10]; 
        Scanner obj=new Scanner(System.in);
        System.out.println("Enter row and column of 1st matrix");
        m=obj.nextInt();
        n=obj.nextInt();
        System.out.println("Enter row and column of 2nd matrix");
        p=obj.nextInt();
        q=obj.nextInt();
        if(n!=p)
             System.out.println("Matrix multiplication is not possible");
        else
             System.out.println("Enter 1st matrix");//reading 1st matrix
          for(i=0;i<m;i++)
           {
             for(j=0;j<n;j++)
                {
                   a[i][j]=obj.nextInt();
                }
           }   
            System.out.println("Enter 2nd matrix");//reading 2nd matrix
          for(i=0;i<p;i++)
           {
             for(j=0;j<q;j++)
                {
                   b[i][j]=obj.nextInt();
                }
           }
           System.out.println("\t 1st matrix is : \n ");//printing 1st matrix
          for(i=0;i<m;i++)
           {
               if(i==m-1)
                      { 
                        System.out.println(" ");  
                      }   
             for(j=0;j<n;j++)
                {
                   
                   System.out.print(" \t "+a[i][j]);
                }
           }   
                System.out.println("\n\t 2nd matrix is : \n");//Printing 2nd matrix
          for(i=0;i<p;i++)
           {
               if(i==p-1)
                      { 
                        System.out.println(" ");  
                       }   
             for(j=0;j<q;j++)
                {
                   
                   System.out.print(" \t "+b[i][j]);
                } 
           }
           System.out.println("\n Product of 1st and 2nd matrix :");//multiplying the matrices
            for(i=0;i<m;i++)
               {
                 for(j=0;j<q;j++)
                   { 
                         for(k=0;k<p;k++)
                       {
                          c[i][j]=a[i][k]*b[k][j]+c[i][j];
                       }
                   }
               }
               for(i=0;i<m;i++)//printing resultant matrix
               {
                   if(i==m-1)
                      { 
                        System.out.println(" ");  
                       }
                 for(j=0;j<q;j++)
                   {
                       System.out.print("\t "+c[i][j]);
                   }
               }
               
      }
    } 

No comments:

Post a Comment

To convert from Upper case to lowercase(A to a)

//converting from Upper to lower(A to a) import java.util.*; class case { public static void main(String args[]) { System.out.pr...