Java program to multiply two given matrices. User need to enter the size of the matrices and values of matrices.

import java.util.Scanner;

class MatrixMultiplication {
	public static void main(String[] args) {
		int i = 0, j = 0, k = 0, p, q, m, n;
		int a[][] = new int[10][10];
		int b[][] = new int[10][10];
		int c[][] = new int[10][10];
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter a matrix row value ");
		p = sc.nextInt();
		System.out.println("Enter a matrix column value");
		q = sc.nextInt();
		System.out.println("Enter b matrix row value ");
		m = sc.nextInt();
		System.out.println("Enter b matrix columnvalue");
		n = sc.nextInt();
		if (q == m) {
			System.out.println("Enter matrxi A values :");
			for (i = 0; i < p; i++) {
				for (j = 0; j < q; j++) {
					a[i][j] = sc.nextInt();
				}
			}
			System.out.println("\nMatrix A values ");
			for (i = 0; i < p; i++) {
				for (j = 0; j < q; j++) {
					System.out.print(" " + a[i][j]);
				}
				System.out.println();
			}
			System.out.println("Enter matrxi B values :");
			for (i = 0; i < m; i++) {
				for (j = 0; j < n; j++) {
					b[i][j] = sc.nextInt();
				}
			}
			System.out.println("\nMatrix B values ");
			for (i = 0; i < m; i++) {
				for (j = 0; j < n; j++) {
					System.out.print(" " + b[i][j]);
				}
				System.out.println();
			}
			System.out.println("\n C Matrix is C is:");
			if (q == m) {
				for (i = 0; i < p; i++) {
					for (j = 0; j < n; j++) {
						c[i][j] = 0;
						for (k = 0; k < q; k++) {
						   c[i][j] = c[i][j] + (a[i][k] * b[k][j]);
						}
					}
				}
			}
			for (i = 0; i < p; i++) {
				for (j = 0; j < n; j++) {
					System.out.print(" " + c[i][j]);
				}
				System.out.println();
			}
		} else {
			System.out.println("Matrix multiplication not possible");
		}
		sc.close();
	}
}

 

OUTPUT:

Enter a matrix row value 
3
Enter a matrix column value
3
Enter b matrix row value 
3
Enter b matrix columnvalue
3
Enter matrxi A values :
2 2 2 2 2 2 3 3 3

Matrix A values 
 2 2 2
 2 2 2
 3 3 3
Enter matrxi B values :
3 3 3 3 3 3 2 2 2

Matrix B values 
 3 3 3
 3 3 3
 2 2 2

 C Matrix is C = A * B Result
 16 16 16
 16 16 16
 24 24 24

Buy Head First Java

Best Book for Java

Beginner's Book