Java Program to Add two Matrices
Last Updated : 20 Jan, 2025
Improve
Given two matrices A and B of the same size, the task is to add them in Java.
Examples:
Input: A[][] = {{1, 2}, {3, 4}} B[][] = {{1, 1}, {1, 1}} Output: {{2, 3}, {4, 5}} Input: A[][] = {{2, 4}, {3, 4}} B[][] = {{1, 2}, {1, 3}} Output: {{3, 6}, {4, 7}}
Program to Add Two Matrices in Java
Follow the Steps to Add Two Matrices in Java as mentioned below:
- Take the two matrices to be added.
- Create a new Matrix to store the sum of the two matrices.
- Traverse each element of the two matrices and add them. Store this sum in the new matrix at the corresponding index.
- Print the final new matrix.
Below is the implementation of the above approach:
// Java program to add two matrices
public class Geeks {
public static void main(String[] args)
{
// Input matrices
int A[][] = { { 1, 2 }, { 3, 4 } };
int B[][] = { { 1, 1 }, { 1, 1 } };
// Dimensions of the matrix
int rows = A.length;
int cols = A[0].length;
// Resultant matrix to store the sum
int sum[][] = new int[rows][cols];
// Adding two matrices
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum[i][j] = A[i][j] + B[i][j];
}
}
// Printing the resultant matrix
System.out.println("Resultant Matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// Print elements on the same line
System.out.print(sum[i][j] + " ");
}
// Move to the next line after printing each row
System.out.println();
}
}
}
Output
Resultant Matrix: 2 3 4 5