|
| 1 | +// Java program for addition of two matrices |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +class GFG { |
| 6 | + |
| 7 | + // Function to print Matrix |
| 8 | + static void printMatrix(int M[][], |
| 9 | + int rowSize, |
| 10 | + int colSize) |
| 11 | + { |
| 12 | + for (int i = 0; i < rowSize; i++) { |
| 13 | + for (int j = 0; j < colSize; j++) |
| 14 | + System.out.print(M[i][j] + " "); |
| 15 | + |
| 16 | + System.out.println(); |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + // Function to add the two matrices |
| 21 | + // and store in matrix C |
| 22 | + static int[][] add(int A[][], int B[][], |
| 23 | + int size) |
| 24 | + { |
| 25 | + int i, j; |
| 26 | + int C[][] = new int[size][size]; |
| 27 | + |
| 28 | + for (i = 0; i < size; i++) |
| 29 | + for (j = 0; j < size; j++) |
| 30 | + C[i][j] = A[i][j] + B[i][j]; |
| 31 | + |
| 32 | + return C; |
| 33 | + } |
| 34 | + |
| 35 | + // Driver code |
| 36 | + public static void main(String[] args) |
| 37 | + { |
| 38 | + int size = 4; |
| 39 | + |
| 40 | + int A[][] = { { 1, 1, 1, 1 }, |
| 41 | + { 2, 2, 2, 2 }, |
| 42 | + { 3, 3, 3, 3 }, |
| 43 | + { 4, 4, 4, 4 } }; |
| 44 | + // Print the matrices A |
| 45 | + System.out.println("\nMatrix A:"); |
| 46 | + printMatrix(A, size, size); |
| 47 | + |
| 48 | + int B[][] = { { 1, 1, 1, 1 }, |
| 49 | + { 2, 2, 2, 2 }, |
| 50 | + { 3, 3, 3, 3 }, |
| 51 | + { 4, 4, 4, 4 } }; |
| 52 | + // Print the matrices B |
| 53 | + System.out.println("\nMatrix B:"); |
| 54 | + printMatrix(B, size, size); |
| 55 | + |
| 56 | + // Add the two matrices |
| 57 | + int C[][] = add(A, B, size); |
| 58 | + |
| 59 | + // Print the result |
| 60 | + System.out.println("\nResultant Matrix:"); |
| 61 | + printMatrix(C, size, size); |
| 62 | + } |
| 63 | +} |
0 commit comments