Addition of Two Matrix in Java
In this example, you will learn and get the program code of Addition of Two Matrix in Java programming.
Rule of Matrix Addition
Here first we will take 2 two-dimensional array with same size, use for loop to add the elements of both matrix(matrix 1 , matrix 2) with same address of row and columns wise and store in another third matrix(Matrix 3), at last print third matrix as result.
Addition of Two Matrix in Java using Scanner
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import java.util.Scanner; class AddTwoMatrix { public static void main(String args[]) { int row,col, i, j; Scanner in = new Scanner(System.in); //Input number of rows and columns System.out.println("Enter the number of rows and columns :"); row = in.nextInt(); col = in.nextInt(); int first[][] = new int[row][col]; int second[][] = new int[row][col]; int add[][] = new int[row][col]; //input elements in first matrix System.out.println("Enter elements of first matrix : "); for ( i = 0 ; i < row ; i++ ) for ( j = 0 ; j < col ; j++ ) first[i][j] = in.nextInt(); //input elements in second matrix System.out.println("Enter elements of second matrix : "); for ( i = 0 ; i < row ; i++ ) for ( j = 0 ; j < col ; j++ ) second[i][j] = in.nextInt(); //Addition of two matrix elements for ( i = 0 ; i < row ; i++ ) for ( j = 0 ; j < col ; j++ ) add[i][j] = first[i][j]+ second[i][j]; //Print elements of third matrix System.out.println("Addition Of Two Matrix :-"); for ( i = 0 ; i < row ; i++ ) { for ( j = 0 ; j < col ; j++ ) { System.out.print(add[i][j]+"\t"); } System.out.println(); } } } |
Output
Check out our other Java Programming Examples