Java – Matrix multiplication

Previous
Next

Program to check whether 2 matrixes can multiply or not:

class Pro
{ 
	public static void main(String[] args) 
	{ 
		int[][] matrixA = { { 1, 2, 3 }, { 4, 5, 6 } }; 
		int[][] matrixB = { { 7, 8 }, { 9, 10 }, { 11, 12 } }; 
  
		int row1 = matrixA.length; 
		int column1 = matrixA[0].length; 
		int row2 = matrixB.length; 
		int column2 = matrixB[0].length; 
  
		if (column1 == row2) { 
			System.out.println("Multiplication Possible"); 
		} 
		else
			System.out.println("Multiplication Not Possible"); 
	} 
}

Matrix Multiplication:

class MatrixMultiplication
{  
	public static void main(String args[])
	{  
		int a[][]={{1, 2, 3},{4, 5, 6},{7, 8, 9}};    
		int b[][]={{1, 2, 3},{4, 5, 6},{7, 8, 9}};    
	    
		int c[][]=new int[3][3];
	    
		for(int i=0;i<3;i++){    
			for(int j=0;j<3;j++){    
				c[i][j]=0;      
				for(int k=0;k<3;k++)      
				{      
					c[i][j]+=a[i][k]*b[k][j];      
				}
			System.out.print(c[i][j]+" "); 
			}
		System.out.println();
		}    
	}
}
Previous
Next

Add Comment

Courses Enquiry Form