Last Updated : 12 Jul, 2025
Given two matrices A and B of the same size, the task is to add them in Java.
Examples:
Program to Add Two Matrices in JavaInput: 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}}
Follow the Steps to Add Two Matrices in Java as mentioned below:
Below is the implementation of the above approach:
Java
// 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();
}
}
}
Resultant Matrix: 2 3 4 5
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4