We can add two matrices in java using multi-dimensional arrays. In java “array of arrays “ approach is used for create multi-dimensional array
Examples:
We have two matrices A and B of same size, and we have to add them in Java by traverse each element of the two matrices. Store this sum in the new matrix at the corresponding index.
Input: A[][] = {{3, 5},{2, 7}} B[][] = {{3, 2},{2, 1}} Output: {{6, 7},{4, 8}}
Example – Program to adding two matrices
public class AddingTwoMatrices { public static void main(String args[]) { int A[][] = { { 3, 5 }, { 2, 7 } }; int B[][] = { { 3, 2 }, { 2, 1 } }; int C[][] = new int[2][2]; //2 rows and 2 columns for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { C[i][j] = A[i][j] + B[i][j]; System.out.print(C[i][j] + " "); } System.out.println(); } } }
Output
6 7
4 8
Example – Using independent method
public class AddingTwoMatrices { public static void main(String[] args) { int a[][] = { { 3, 5 }, { 2, 7 } }; int b[][] = { { 3, 2 }, { 2, 1 } }; int[][] sum = addMatrices(a, b); System.out.println("The sum of two matrices is: "); printMatrix(sum); } public static int[][] addMatrices(int[][] a, int[][] b) { int rows = a.length; int columns = a[0].length; int[][] result = new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { result[i][j] = a[i][j] + b[i][j]; } } return result; } public static void printMatrix(int[][] matrix) { int rows = matrix.length; int columns = matrix[0].length; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }
Output
The sum of two matrices is:
6 7
4 8