Follow @devglan

# Write a Java Program to Add Two 2D Matrix

## Description

A matrix is a rectangular array of numbers or expressions arranged in rows and columns.Below is the java program to add two 2D matrices.We can change the dimension variables accordingly for 3D and 4D matrix.

**MatrixAddition.java**

public class MatrixAddition { public static void main(String[] args) { int[][] matrix1 ={ {10,12},{10,12} }; int[][] matrix2 ={ {10,12},{10,12} }; addMatrices(matrix1, matrix2); } public static int[][] addMatrices(int[][] matrix1 , int[][] matrix2){ int m=2 ; int n =2; int sum[][] = new int[m][n]; for (int c = 0 ; c < m ; c++ ){ for (int d = 0 ; d < n ; d++ ){ sum[c][d] = matrix1[c][d] + matrix2[c][d]; } } for ( int c = 0 ; c < m ; c++ ) { for ( int d = 0 ; d < n ; d++ ) System.out.print(sum[c][d]+"\t"); System.out.println(); } return sum; }

## Explanation

#### Click to Suggest Your Own Explanation

In the above program we have two 2D matrix.Hence, the resulting matrix will have two cols and two rows.Here m and n stands for the rows and columns respectively. The first for loop continues for each row the inner loop continues for the columns present in a row.
[{00}] elmement in