|
| 1 | +//Addition of 2 n*n matrices |
| 2 | +//this program works for m*n matrices also! |
| 3 | +import java.util.Scanner; |
| 4 | +public class matrixAddition { |
| 5 | + |
| 6 | + public static void main(String[] args) { |
| 7 | + Scanner reader=new Scanner(System.in); |
| 8 | + |
| 9 | + int matrix_1[][]; |
| 10 | + int matrix_2[][]; |
| 11 | + int add_matrix[][]; |
| 12 | + |
| 13 | + //taking input of number of rows and columns from user |
| 14 | + System.out.println("enter row size of both matrices to be added :"); |
| 15 | + int row = reader.nextInt(); |
| 16 | + System.out.println("enter column size of both matrices to be added :"); |
| 17 | + int col = reader.nextInt(); |
| 18 | + |
| 19 | + // declaring matrices of user defined rows and columns |
| 20 | + matrix_1 = new int[row][col]; |
| 21 | + matrix_2 = new int[row][col]; |
| 22 | + add_matrix = new int[row][col]; |
| 23 | + |
| 24 | + //entering elements in matrix 1 |
| 25 | + System.out.println("Enter elemtents in Matrix 1\n"); |
| 26 | + for(int i=0; i<row; i++){ |
| 27 | + for(int j=0; j<col; j++){ |
| 28 | + matrix_1[i][j] = reader.nextInt(); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + //entering elements in matrix 2 |
| 33 | + System.out.println("Enter elemtents in Matrix 2\n"); |
| 34 | + for(int i=0; i<row; i++){ |
| 35 | + for(int j=0; j<col; j++){ |
| 36 | + matrix_2[i][j] = reader.nextInt(); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + // adding matrix 1 and 2 |
| 41 | + for( int i=0; i<row; i++){ |
| 42 | + for(int j=0; j<col; j++){ |
| 43 | + add_matrix[i][j] = matrix_1[i][j] + matrix_2[i][j]; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + // Printing output matrix |
| 48 | + System.out.println("Resultant Matrix: \n"); |
| 49 | + for(int i=0; i<row; i++){ |
| 50 | + for(int j=0; j<col; j++){ |
| 51 | + System.out.print(add_matrix[i][j]+" "); |
| 52 | + |
| 53 | + } System.out.println(); |
| 54 | + } |
| 55 | + |
| 56 | + |
| 57 | + |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments