Computer Science, asked by malikheer41, 3 months ago

Write a program to add two matices (two dimensional array). Input the order of matrix. The matrices must of the same size to be added, if not they can not be added(check for it). Get the input for each element of the first matrix and then second matrix, add the two matrix and store the value in third matrix. Finally display the all the martices.​

Answers

Answered by Oreki
0

import java.util.Arrays;

import java.util.Scanner;

public class Matrices {

   // A method for assigning its elements to the matrix

   static int[ ][ ] assign(String name) {

       Scanner sc = new Scanner(System.in);

       // Accepting the order of the matrix

       System.out.println("\nEnter the order of the Matrix " + name + " -");

       int[ ][ ] matrix = new int[sc.nextInt( )][sc.nextInt( )];

       // Accepting the elements of the matrix

       System.out.println("Enter elements of matrix " + name + " -");

       for (int i = 0; i < matrix.length; i++)

           for (int j = 0; j < matrix[0].length; j++)

               matrix[i][j] = sc.nextInt( );

       return matrix;

   }

   public static void main(String[ ] args) {

       int[ ][ ] matrix_A = assign("A"),

                  matrix_B = assign("B");

       // Checking the orders of the matrices

       if (matrix_A.length == matrix_B.length &&  

               matrix_A[0].length == matrix_B[0].length) {

           int[ ][ ] matrix_C = new int[matrix_A.length][matrix_A[0].length];

           

           // Adding the two matrices and storing it in a third matrix

           for (int i = 0; i < matrix_C.length; i++)

               for (int j = 0; j < matrix_C[0].length; j++)

                   matrix_C[i][j] = matrix_A[i][j] + matrix_B[i][j];

           // Displaying the matrices

          for (int i = 0; i < matrix_C.length; i++) {

               String alignment = (matrix_C.length / 2 == i) ?  

                       "  %s  +  %s   =   %s" : "  %s     %s       %s";

               System.out.printf(alignment + "\n", Arrays.toString(matrix_A[i]),

                                                   Arrays.toString(matrix_B[i]),

                                                   Arrays.toString(matrix_C[i]));

           }

       } else System.out.println("Can't add matrices of different orders");

   }

}

Attachments:
Answered by roychhaya63
0

Answer:

Hope iit helps you thanks bye

Attachments:
Similar questions