Java Program for Matrix Multiplication

Here you will get java program for matrix multiplication.

Suppose we have matrix A with number of rows and columns as m and n. Let B be a matrix with number of rows and columns as p and q. Their multiplication is possible only if number of columns of matrix A is equal to number of rows of matrix B i.e. n should be equal to p. The resultant matrix is of order mxq.

Java Program for Matrix Multiplication

Also Read: Java Program for Matrix Addition

Java Program for Matrix Multiplication

import java.util.Scanner;

public class JavaMatrixMultiplication {
	public static void main(String args[]) {
		int a[][], b[][], c[][], m, n, p, q, i, j, k;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter number of rows and columns of first matrix:");
		m = sc.nextInt();
		n = sc.nextInt();
		
		System.out.println("Enter number of rows and columns of second matrix:");
		p = sc.nextInt();
		q = sc.nextInt();
		
		if(n != p) {
			System.out.println("Multiplication can't be done");
		}
		else {
			a = new int[m][n];
			b = new int[p][q];
			c = new int[n][p];
			
			System.out.println("Enter elements of first matrix row wise:");
			for(i = 0; i < m; ++i) {
				for(j = 0; j < n; ++j) {
					a[i][j] = sc.nextInt();
				}
			}
			
			System.out.println("Enter elements of second matrix row wise:");
			for(i = 0; i < p; ++i) {
				for(j = 0; j < q; ++j) {
					b[i][j] = sc.nextInt();
				}
			}
				
			for(i = 0; i < m; ++i) {				
				for(j = 0; j < q; ++j) {
					for(k = 0; k < n; ++k) {
						c[i][j] = c[i][j] + a[i][k] * b[k][j];
					}
				}
			}
			
			System.out.println("Matrix after multiplication:");
			for(i = 0; i < m; ++i) {
				for(j = 0; j < q; ++j) {
					System.out.print(c[i][j] + " ");
				}
				
				System.out.print("\n");
			}
		}
		
		sc.close();
	}
}

Output

Enter number of rows and columns of first matrix:
2
2
Enter number of rows and columns of second matrix:
2
2
Enter elements of first matrix row wise:
4 5
6 7
Enter elements of second matrix row wise:
1 2
4 3
Matrix after multiplication:
24 23
34 33

Leave a Comment

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