For adding two matrix we have to follow some steps . Let’s see how we can add two matrix in java.
- First we have two matrix with same size of row and column , so we first take input of row and column.
- After getting number of row and column , we take input of first matrix then second.
- Create in another matrix to store sum of those two matrix.
- Traverse each element of the two matrices and add them. Store this sum in the new matrix at the corresponding index.
- Finally we print the result of addition that we have stored in another third matrix.
Simple program to add two matrix in java
import java.util.Scanner; class MatrixAddition { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter number of rows: "); int rows = in.nextInt(); System.out.print("Enter number of columns: "); int columns = in.nextInt(); int a[][] = new int[rows][columns]; int b[][] = new int[rows][columns]; System.out.println("Give the Elements for first matrix"); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { a[i][j] = in.nextInt(); } } System.out.println("Elements for second matrix"); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { b[i][j] = in.nextInt(); } } int c[][] = new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { c[i][j] = a[i][j] + b[i][j]; } } System.out.println("The sum of the two matrices is"); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { System.out.print(c[i][j] + " "); } System.out.println(" "); } } }
Output
Enter number of rows: 2
Enter number of columns: 3
Give the Elements for first matrix
1
2
3
4
5
6
Enter the Elements for second matrix
6
5
4
3
2
1
The sum of the two matrices is
7 7 7
7 7 7