Java Program to add two given Matrices
- September 02, 2020
- by
Java Program to add two given Matrices
In this Java Program, we add two given matrices.
Array is a data structure consisting of collections of elements each identified by atleast one array index or key.
E.g. If you want to store 5 numbers in an array,
datatype arrayname [arraysize];
int a[5];
A matrix is a multidimensional array which consists of columns and rows.
For the addition of two matrices, we need two matrices of same dimension, which means they should have same number of rows and columns.
For this Program, we declare the matrix as a 2D array.
| 1 1 1 1 |
| 2 3 5 2 |
Declaration of matrix as 2D array :
int [][] MatrixA = { {1, 1, 1, 1}, {2, 3, 5, 2}};
We use for loop for addition of the two matrices and store the addition values into the sum matrix.
For E.g.
sum[0][0] = MatrixA[0][0] + MatrixB[0][0], similarly,
sum[0][1] = MatrixA[0][1] + MatrixB[0][1] and so on.
Program :
public class AddTwoMatrix {
public static void main(String [] args)
{
int rows = 2, columns = 4;
//Declaring the two matrices as multi-dimensional arrays
int[][] MatrixA = { {1, 1 , 1, 1}, {2, 3, 5, 2} };
int[][] MatrixB = { {2, 3, 4, 5,}, {2, 2, 4, -4} };
//Declaring a matrix sum, that will be the sum of MatrixA and MatrixB
//The sum matrix will have the same rows and columns as the given matrices.
int[][] sum = new int[rows][columns];
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
sum[i][j] = MatrixA[i][j] + MatrixB[i][j];
}
}
//Displaying the sum matrix
System.out.println("Sum of the given matrices is:");
for(int i =0; i < rows; i++)
{
for(int j =0; j < columns; j++)
{
System.out.print(sum[i][j] + " ");
}
System.out.println();
}
}
}
Output :
Sum of the given matrices is:
3 4 5 6
4 5 9 -2
For Execution of the same, do visit my YouTube Channel :


0 comments:
Post a Comment