21 Dec 2017

Write a program to find the sum of the two matrix of size (NxN).

Here is the program to Addition of  two given matrix of size NxN. we see here that how Addition performed .so have a look here from given example.



import java.util.Scanner;

public class AdditionTwoMatrix {
          public static void main(String[] args) {

                   Scanner scanner = new Scanner(System.in);
                   System.out.print("Enter the Number of rows: ");
                   int rows = scanner.nextInt();

                   System.out.print("Enter the Number of columns: ");
                   int columns = scanner.nextInt();

                   int[][] matrix1 = new int[rows][columns];
                   int[][] matrix2 = new int[rows][columns];

                   System.out.println("Enter the Elements of First matrix");
                   for (int i = 0; i < rows; i++) {
                             String num[] = new Scanner(System.in).nextLine().split(" ");
                             for (int j = 0; j < columns; j++) {
                                      matrix1[i][j] = Integer.parseInt(num[j]);
                                      ; // elements of first matrix.
                             }
                   }

                   System.out.println("Enter the Element of Second Matrix");
                   for (int i = 0; i < rows; i++) {
                             String num[] = new Scanner(System.in).nextLine().split(" ");
                             for (int j = 0; j < columns; j++) {
                                      matrix2[i][j] = Integer.parseInt(num[j]);
                                      ; // elements of Second matrix.
                             }
                   }

                   int[][] matrix3 = new int[rows][columns];

                   for (int i = 0; i < rows; i++) {
                             for (int j = 0; j < columns; j++) {
                                      matrix3[i][j] = matrix1[i][j] + matrix2[i][j];
                             }
                   }
                   System.out.println("The Addition of Two Matrices is");
                   for (int i = 0; i < rows; i++) {
                             for (int j = 0; j < columns; j++) {
                                      System.out.print(matrix3[i][j] + "  ");
                             }
                             System.out.println();
                   }
          }
}

Output: