Q:

Write a Java Program for Addition of Two Matrices

belongs to collection: Java Arrays Solved Programs

0

To add two matrices in Java Programming, you have to ask to the user to enter the elements of both the n*n matrix, now start adding the two matrix to form a new/third matrix which is the addition result of the two given matrix.

After adding the two matrices, display the third matrix which is the result of the addition of the two matrices.

  • Following Java Program add two n*n matrices to form the third matrix :

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

SOURCE CODE ::

import java.util.Scanner;
 
public class Add_matrices {
   public static void main(String args[])
   {
      int m, n, c,d;
      Scanner in = new Scanner(System.in);
 
      System.out.println("Enter the number of rows and columns of matrix");
      m = in.nextInt();
      n = in.nextInt();
 
      int first[][] = new int[m][n];
      int second[][] = new int[m][n];
      int sum[][] = new int[m][n];
 
      System.out.println("Enter the elements of first matrix");
 
      for (  c = 0 ; c < m ; c++ )
         for ( d = 0 ; d < n ; d++ )
         {
            System.out.print(c+""+d+" Element : ");
            first[c][d] = in.nextInt();
         }
 
      System.out.println("Enter the elements of second matrix");
 
      for ( c = 0 ; c < m ; c++ )
         for ( d = 0 ; d < n ; d++ )
         {
             System.out.print(c+""+d+" Element : ");
            second[c][d] = in.nextInt();
         }
      
      //--------Add two matrix-----------------------------------
      
      for ( c = 0 ; c < m ; c++ )
         for ( d = 0 ; d < n ; d++ )
             sum[c][d] = first[c][d] + second[c][d];
 
      System.out.println("Sum of entered matrices:-");
 
      for ( c = 0 ; c < m ; c++ )
      {
         for ( d = 0 ; d < n ; d++ )
            System.out.print(sum[c][d]+"\t");
 
         System.out.println();
      }
   }
}
 
 

OUTPUT ::

 
Enter the number of rows and columns of matrix
2
2
Enter the elements of first matrix
00 Element : 1
01 Element : 2
10 Element : 3
11 Element : 4
Enter the elements of second matrix
00 Element : 1
01 Element : 2
10 Element : 3
11 Element : 4
Sum of entered matrices:-
2       4       
6       8

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Write a Java Program for Subtraction of Two Matric... >>
<< Write a Java Program to input and print n elements...