English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to add two matrices using multi-dimensional arrays in Java.
public class AddMatrices { public static void main(String[] args) { int rows = 2, columns = 3; int[][] firstMatrix = { {2, 3, 4}, {5, 2, 3}; int[][] secondMatrix = { {-4, 5, 3}, {5, 6, 3}; //Addition of two matrices int[][] sum = new int[rows][columns]; for (int i = 0; i < rows; i++)} for (int j = 0; j < columns; j++)} sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j]; } } //Display the result System.out.println("The sum of the two matrices is: "); for (int[] row : sum) { for (int column : row) { System.out.print(column + " "); } System.out.println(); } } }
When running the program, the output is:
The sum of the two matrices is: -2 8 7 10 8 6
In the above program, the two matrices are stored in2In the d array, that is firstMatrix and secondMatrix. We also define the number of rows and columns, and store them in variables row and column respectively
Then, we initialize a new array for the given row and column, called sum. This matrix array stores the addition of the given matrix.
We traverse each index of the two arrays to add and store the result.
Finally, we use the for (foreach variable) loop to traverse each element of the sum array to print the element.