Write a Java program to Add Two Matrices
Problem Description
In this post, we will write a sample java program to add two matrices. We would prompt the matrix dimensions and the matrix elements from the user. We will calculate the matrix sum as a third matrix and display the output in the console window. At the end of the post, we will display a sample output of the program.
Java Program
package matrix; import java.util.Scanner; // Demo program to add two matrices // www.TestingDocs.com public class AddMatrixDemo { public static void main(String args[]) { Scanner in = new Scanner(System.in); System.out.println("Please enter the number of Rows and Columns of Matrix:= "); //intialise rows of matrix as m int m = in.nextInt(); //intialise columns of matrix as n int n = in.nextInt(); //intialise the first matrix with m as rows and n as columns int firstMatrix[][] = new int[m][n]; //intialise the second matrix with m as rows and n as columns int secondMatrix[][] = new int[m][n]; //intialise the sum of two matrices with m as rows and n as columns int sumOfMatrix[][] = new int[m][n]; System.out.println("Enter the elements of First Matrix:= "); for (int i=0;i<m;i++) for (int j=0;j<n;j++) firstMatrix[i][j] = in.nextInt(); System.out.println("Enter the elements of Second Matrix:= "); for (int i=0;i<m;i++) for (int j=0;j<n;j++) secondMatrix[i][j]=in.nextInt(); //declare the elements of both matrices as i & j for (int i=0;i<m;i++) for (int j=0;j<n;j++) sumOfMatrix[i][j]=firstMatrix[i][j] + secondMatrix[i][j]; System.out.println("Sum of the Two Matrices: "); for (int i=0;i<m;i++) { for (int j=0;j<n;j++) { System.out.print(sumOfMatrix[i][j] + " "); } System.out.println(); } } }
Screenshot
Sample program output
Please enter the number of Rows and Columns of Matrix:=
2 3
Enter the elements of First Matrix:=
3 7 9
6 4 5
Enter the elements of Second Matrix:=
4 7 9
2 1 6
Sum of the Two Matrices:
7 14 18
8 5 11