Matrix Addition
Matrix Addition
Matrix Addition
We can add two matrices in java using binary + operator. A matrix is also known as array of arrays.
We can add, subtract and multiply matrices.
Java program to add two matrices – The following Java Code will let you know how to perform two matrix
addition using Java. We can write the Program in three Possible ways. Here it is,
Addition of two matrices can be carried if and only if both the matrices are in the same order. In matrix addition,
each term of one matrix is added to the other matrix’s term, at the same location, i.e. the term at first row first
column of Matrix 1 will be added to the term at first row first column of Matrix 2 and so on. A pictorial example is
given below.
Addition Of Two Matrices – Using For Loop
1) If both matrices are of the same size then only we can add the matrices.
3) Read row number, column number and initialize the double dimensional arrays
mat1[][],mat2[][],res[][] with same row number, column number.
4)Store the first matrix elements into the two-dimensional array mat1[][] using two for
loops. i indicates row number, j indicates column index. Similarly matrix 2 elements in to
mat2[][].
i=0
do loop
j=0
do loop
mat1[i][j] + mat2[i][j] and insert the result in to res[i][j].
Increase the j value. checks the condition j<col.
Increase the i value. Then checks the condition j<row.
2) Print res[][] then we will get the addition of two matrices.
import java.util.Scanner;
System.out.println("Enter the elements of matrix1");
class AddMatrix i=0;
{ do
public static void main(String args[]) {
{ j=0;
int row, col,i,j; do
Scanner in = new Scanner(System.in); {
mat1[i][j] = in.nextInt();
System.out.println("Enter the number of rows"); j++;
row = in.nextInt(); }while(j < col);
i++;
System.out.println("Enter the number columns");
col = in.nextInt(); } while ( i < row);