Addition of matrices in Java
Track completion, mastery, and revision.
In computer science and mathematics, a matrix is represented as a two-dimensional (2D) array. Matrix addition is the operation of adding corresponding elements of two matrices together to produce a third, resultant matrix.
In this tutorial, you will learn how to write a Java program to dynamically take two matrices from a user, add them, and display both the input matrices along with their sum.
The Rule of Matrix Addition
Before writing the code, there is one fundamental mathematical rule to keep in mind:
💡 Key Rule: Two matrices can only be added if they have identical dimensions. This means both matrices must have the exact same number of rows ($R$) and columns ($C$).
If Matrix $A$ is of size $2 \times 3$, Matrix $B$ must also be of size $2 \times 3$. The resulting Matrix $C$ will also have a size of $2 \times 3$, where:
$$\text{Result}[i][j] = A[i][j] + B[i][j]$$
Algorithm
To implement this program in Java, we will follow these steps:
- Input Dimensions: Prompt the user to enter the number of rows ($R$) and columns ($C$).
- Initialize Matrices: Create two 2D arrays (
matrixAandmatrixB) of size $R \times C$. - Populate Matrices: Use nested loops to read integer inputs from the user for both matrices.
- Perform Addition: Create a third 2D array (
sumMatrix) of size $R \times C$. Use nested loops to add corresponding elements from the first two matrices and store the result in the third. - Display Results: Print the original matrices and the final summation matrix in a clean, readable grid format.
Java Implementation
Here is the complete, well-structured Java program to perform matrix addition:
import java.util.Scanner;
public class AddMatrix {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int r, c, i, j;
// Step 1: Get Matrix Dimensions
System.out.print("Enter Dimensions of Matrix (Row and Column): ");
r = inp.nextInt();
c = inp.nextInt();
// Step 2: Initialize Matrices
int[][] a = new int[r][c];
int[][] b = new int[r][c];
// Step 3: Input elements for the First Matrix
System.out.println("Enter elements for the First Matrix: ");
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
System.out.print("Enter element at [" + i + "][" + j + "]: ");
a[i][j] = inp.nextInt();
}
}
// Input elements for the Second Matrix
System.out.println("\nEnter elements for the Second Matrix: ");
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
System.out.print("Enter element at [" + i + "][" + j + "]: ");
b[i][j] = inp.nextInt();
}
}
// Step 4: Calculate the Summation Matrix
int[][] sum = new int[r][c];
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
// Adding corresponding elements
sum[i][j] = a[i][j] + b[i][j];
}
}
// Step 5: Display the Results
System.out.println("\nFirst Matrix: ");
display(a, r, c);
System.out.println("\nSecond Matrix: ");
display(b, r, c);
System.out.println("\nResultant Matrix after Addition: ");
display(sum, r, c);
inp.close();
}
/**
* Helper method to display a 2D array in grid format
*/
public static void display(int[][] arr, int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Sample Output
If you run the program with a $2 \times 3$ matrix size, the terminal execution will look like this:
Enter Dimensions of Matrix (Row and Column): 2 3
Enter elements for the First Matrix:
Enter element at [0][0]: 1
Enter element at [0][1]: 2
Enter element at [0][2]: 3
Enter element at [1][0]: 4
Enter element at [1][1]: 5
Enter element at [1][2]: 6
Enter elements for the Second Matrix:
Enter element at [0][0]: 7
Enter element at [0][1]: 8
Enter element at [0][2]: 9
Enter element at [1][0]: 6
Enter element at [1][1]: 5
Enter element at [1][2]: 4
First Matrix:
1 2 3
4 5 6
Second Matrix:
7 8 9
6 5 4
Resultant Matrix after Addition:
8 10 12
10 10 10
Complexity Analysis
Understanding the performance of your code is vital for technical interviews:
- Time Complexity: $\mathcal{O}(R \times C)$ We use nested loops to traverse through every element of the matrices for input, addition, and printing. Thus, the time taken scales linearly with the total number of elements.
- Space Complexity: $\mathcal{O}(R \times C)$
We allocate additional memory for the
summatrix to store the results of the addition.
Finished reading?