Addition of Two Matrix in Java

In this example, You learn about java program for addition of two matrix. 

Here you learn addition of two matrix in Java, You are given an two dimensional arrays and the task of the program to addition of two matrix in java.

Addition of Two Matrix in Java

import java.util.Scanner;

public class AddTwoMatrix
{
 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++ )
            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++ )
            second[c][d] = in.nextInt();
    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 3

Enter the elements of first matrix
2 3 4 
5 6 8

Enter the elements of second matrix
9 10 11
13 12 1

Sum of entered matrices:-
11 13 15	
18 18 9

If you have any doubts, Please let me know

Previous Post Next Post

Contact Form