Introduction
In Part 1, we learned:
- What a matrix is
- Conditions for matrix multiplication
- The Row × Column rule
- How to perform matrix multiplication manually
Now it’s time to convert that knowledge into a Java program.
By the end of this tutorial, you will be able to:
- Accept two matrices from the user.
- Check whether multiplication is possible.
- Multiply the matrices.
- Display the result matrix.
- Understand the purpose of every loop in the program.
Algorithm for Matrix Multiplication
Before writing the code, let’s understand the algorithm.
Step 1
Read the dimensions of the first matrix.
firstMatrixRows
firstMatrixColumns
Step 2
Read the dimensions of the second matrix.
secondMatrixRows
secondMatrixColumns
Step 3
Check whether multiplication is possible.
If firstMatrixColumns != secondMatrixRows
Display "Multiplication Not Possible"
Else
Continue
Step 4
Create three matrices.
First Matrix
Second Matrix
Result Matrix
Step 5
Read all elements of the first matrix.
Step 6
Read all elements of the second matrix.
Step 7
Multiply the matrices.
Step 8
Display the result matrix.
Understanding the Three Nested Loops
This is the heart of the program.
We already know that
(m × n)
×
(n × p)
=
(m × p)
The three loops represent:
for(row)
Moves through
Rows of First Matrix
for(column)
Moves through
Columns of Second Matrix
for(common)
Moves through
Columns of First Matrix
=
Rows of Second Matrix
Remember this forever.
Row
↓
Column
↓
Common Dimension
Complete Java Program
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input dimensions of first matrix
System.out.print("Enter number of rows of First Matrix: ");
int firstMatrixRows = sc.nextInt();
System.out.print("Enter number of columns of First Matrix: ");
int firstMatrixColumns = sc.nextInt();
// Input dimensions of second matrix
System.out.print("Enter number of rows of Second Matrix: ");
int secondMatrixRows = sc.nextInt();
System.out.print("Enter number of columns of Second Matrix: ");
int secondMatrixColumns = sc.nextInt();
// Check whether multiplication is possible
if (firstMatrixColumns != secondMatrixRows) {
System.out.println("\nMatrix multiplication is NOT possible.");
System.out.println(
"Columns of First Matrix must be equal to Rows of Second Matrix.");
sc.close();
return;
}
// Create matrices
int firstMatrix[][] =
new int[firstMatrixRows][firstMatrixColumns];
int secondMatrix[][] =
new int[secondMatrixRows][secondMatrixColumns];
int resultMatrix[][] =
new int[firstMatrixRows][secondMatrixColumns];
// Input first matrix
System.out.println("\nEnter elements of First Matrix:");
for (int row = 0; row < firstMatrixRows; row++) {
for (int column = 0; column < firstMatrixColumns; column++) {
firstMatrix[row][column] = sc.nextInt();
}
}
// Input second matrix
System.out.println("\nEnter elements of Second Matrix:");
for (int row = 0; row < secondMatrixRows; row++) {
for (int column = 0; column < secondMatrixColumns; column++) {
secondMatrix[row][column] = sc.nextInt();
}
}
// Matrix Multiplication
for (int row = 0; row < firstMatrixRows; row++) {
for (int column = 0; column < secondMatrixColumns; column++) {
for (int common = 0;
common < firstMatrixColumns;
common++) {
resultMatrix[row][column] +=
firstMatrix[row][common] *
secondMatrix[common][column];
}
}
}
// Display Result Matrix
System.out.println("\nResult Matrix:");
for (int row = 0; row < firstMatrixRows; row++) {
for (int column = 0; column < secondMatrixColumns; column++) {
System.out.print(resultMatrix[row][column] + "\t");
}
System.out.println();
}
sc.close();
}
}
Understanding the Program Step by Step
Let’s understand every important section of the program.
Step 1: Reading Matrix Dimensions
System.out.print("Enter number of rows of First Matrix: ");
int firstMatrixRows = sc.nextInt();
System.out.print("Enter number of columns of First Matrix: ");
int firstMatrixColumns = sc.nextInt();
Here, we ask the user to enter the size of the first matrix.
For example,
Rows = 2
Columns = 3
This means the first matrix will contain
2 Rows
3 Columns
Similarly,
System.out.print("Enter number of rows of Second Matrix: ");
int secondMatrixRows = sc.nextInt();
System.out.print("Enter number of columns of Second Matrix: ");
int secondMatrixColumns = sc.nextInt();
Suppose the user enters
Rows = 3
Columns = 2
Step 2: Checking Whether Multiplication is Possible
This is the most important validation.
if (firstMatrixColumns != secondMatrixRows) {
System.out.println("Matrix multiplication is NOT possible.");
return;
}
Suppose the user enters
First Matrix
2 × 3
Second Matrix
4 × 2
Compare
First Matrix Columns = 3
Second Matrix Rows = 4
Since
3 ≠ 4
Multiplication cannot be performed.
The program immediately stops.
This prevents invalid calculations and runtime errors.
Step 3: Creating the Matrices
int firstMatrix[][] =
new int[firstMatrixRows][firstMatrixColumns];
Creates the first matrix.
Similarly,
int secondMatrix[][] =
new int[secondMatrixRows][secondMatrixColumns];
creates the second matrix.
Finally,
int resultMatrix[][] =
new int[firstMatrixRows][secondMatrixColumns];
creates the result matrix.
Notice carefully.
The result matrix uses
Rows of First Matrix
Columns of Second Matrix
Exactly as we learned in Part 1.
Step 4: Reading Matrix Elements
for(int row=0; row<firstMatrixRows; row++)
{
for(int column=0;
column<firstMatrixColumns;
column++)
{
firstMatrix[row][column]=sc.nextInt();
}
}
The outer loop moves through every row.
The inner loop moves through every column.
Together they read every element of the matrix.
Exactly the same logic is used for the second matrix.
Step 5: Matrix Multiplication
This is the most important part of the program.
for(int row=0; row<firstMatrixRows; row++)
{
for(int column=0;
column<secondMatrixColumns;
column++)
{
for(int common=0;
common<firstMatrixColumns;
common++)
{
resultMatrix[row][column]+=
firstMatrix[row][common]
*
secondMatrix[common][column];
}
}
}
Remember the meaning of every variable.
row
↓
Current Row of First Matrix
column
↓
Current Column of Second Matrix
common
↓
Common Dimension
Columns of First Matrix
Rows of Second Matrix
This exactly follows the Row × Column rule.
Why is the Inner Loop Named “common”?
Many books use
k
Instead of
common
However,
common
is much easier to understand.
It represents the
Common Dimension
Columns of First Matrix
=
Rows of Second Matrix
For every value of
common
the program multiplies one element from the selected row of the first matrix with the corresponding element from the selected column of the second matrix.
Sample Input
Enter number of rows of First Matrix:
2
Enter number of columns of First Matrix:
3
Enter number of rows of Second Matrix:
3
Enter number of columns of Second Matrix:
2
Enter elements of First Matrix
1 2 3
4 5 6
Enter elements of Second Matrix
7 8
9 10
11 12
Output
Result Matrix
58 64
139 154
Key Takeaways
- Always check whether multiplication is possible before performing any calculations.
- Matrix multiplication is possible only when the columns of the first matrix equal the rows of the second matrix.
- The result matrix size is Rows of First Matrix × Columns of Second Matrix.
- The program uses three nested loops:
- The first loop selects each row of the first matrix.
- The second loop selects each column of the second matrix.
- The third loop traverses the common dimension and computes the dot product.
- Using descriptive variable names like
row,column, andcommonmakes the algorithm much easier to understand than using generic variables such asi,j, andk.