In this post we focuses on adding two matrices.Before adding two matrices we need two matrices of same order.i.e is number of rows,columns in matrix 1 should be equaled to number of rows,columns in matrix 2.The procedure for adding two matrix is:
1. Input:Take two,matrix of same order from the user,can be of different elements.
2. Procedure:For summation of two matrix we need to add the elements of the corresponding position and store them in the same position.
3. Display:After the summation we display the result stored in the matrix.
By following the above steps we can write a simple code:
import java.util.*; class addition { int n,i,j; void setdata() { Scanner in = new Scanner(System.in); int[][] mat1 = new int[n+1][n+1]; int[][] mat2 = new int[n+1][n+1]; int[][] resltmat = new int[n+1][n+1]; System.out.println("Enter the elements of 1 matrix:"); for(i=1;i < n+1;i++) { for(j=1;j < n+1;j++) { System.out.println("Enter the element of "+ i +" row "+ j +" column:"); mat1[i][j] = in.nextInt(); }// end of j loop }// end of i loop System.out.println("Enter the elements of 2 matrix:"); for(i=1;i < n+1;i++) { for(j=1;j < n+1;j++) { System.out.println("Enter the element of "+ i +" row "+ j +" column:"); mat2[i][j] = in.nextInt(); }// end of j loop }// end of i loop System.out.println("Resultant matrix is:\n"); for(i=1;i < n+1;i++) { for(j=1;j < n+1;j++) { resltmat[i][j] = mat1[i][j]+mat2[i][j]; //adds the elements of the matrxi 1,2 System.out.print(resltmat[i][j] + " "); } System.out.print("\n\n"); } } } class matadd { public static void main(String arg[]) { Scanner in = new Scanner(System.in); addition ob = new addition(); System.out.print("Enter the order of the matrix you need to enter:"); ob.n=in.nextInt(); ob.setdata(); } }
The output of the above program is:
You can download the source code.
Pingback: Multiplication of two matrix in java | letusprogram....!!!