In this tutorial, first we will learn algorithm to add two matrices then we will learn to write the how to add two matrices in java using scanner but before writing the code in java let's first understand what is the condition to add two matrices.
Note:
Addition of two matrices is possible if and only if the number of rows and number of columns of both matrices are same.
If you are not able to understand the above
definition, then look at the example given
below.
Algorithm to Add Two Matrices:-
Step 1: Input number of rows (r).
Step 2: Input number of columns (c).
Step 3: Input elements of First Matrix.
Step 4: Input elements of Second Matrix.
Step 5: Declare a third matrix.
Step 6: Add both matrices and store result in third matrix.
Step 7: Print the resultant matrix in matrix format.
Below, in this post, I have have written a short and easy to understand java program below which accepts elements of two matrices from the user using scanner input and prints the addition of the matrices in matrix form.
Basically, the logic I have implemented in this program is pretty easy to understand.
First, I will ask the user to enter the number of rows and columns, then the user will enter the elements of both matrix one by one, after that I will use for loop and print all the elements in matrix format.
Java Program to Add Two Matrices
import java.util.*;
class Sum_of_Two_Matrices
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of Rows");
int r=sc.nextInt();
System.out.println("Enter the number of Columns");
int c=sc.nextInt();
int arr[][]=new int[r][c];
int brr[][]=new int[r][c];
int crr[][]=new int[r][c];
System.out.println("Enter the elements of First Matrix");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
arr[i][j]=sc.nextInt();
}
}
System.out.println("First Matrix is :");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println("");
}
System.out.println("Enter the elements of Second Matrix");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
brr[i][j]=sc.nextInt();
}
}
System.out.println("Second Matrix is :");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print(brr[i][j]+" ");
}
System.out.println("");
}
System.out.println("Third Matrix is :");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
crr[i][j]=arr[i][j]+brr[i][j];
System.out.print(crr[i][j]+" ");
}
System.out.println("");
}
}
}
--------------
OUTPUT:-
-------------
Enter the number of Rows
3
Enter t he number of Columns
3
Enter the elements of First Matrix
1
4
2
5
3
6
7
8
9
First Matrix is :
1 4 2
5 3 6
7 8 9
Enter the elements of Second Matrix
1
2
3
6
5
4
7
8
9
Second Matrix is :
1 2 3
6 5 4
7 8 9
Third Matrix is :
2 6 5
11 8 10
14 16 18
----------------
0 Comments
Just write down your question to get the answer...