Given two 3×3 matrix the task is to calculate and display the sum of the matrices.
Example:
| 3 | 1 | 4 |
| 2 | 4 | 7 |
| 6 | 3 | 1 |
+
| 2 | 1 | 3 |
| 6 | 5 | 2 |
| 1 | 2 | 0 |
=
| 5 | 2 | 7 |
| 8 | 9 | 9 |
| 7 | 5 | 1 |
Java
import java.util.*;
class SumTwoMatrix
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[3][3];
int b[][]=new int[3][3];
int sum[][]=new int[3][3];
System.out.println("Enter matrix (A) elements:-");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
a[i][j]=sc.nextInt();
}
}
System.out.println("Enter matrix (B) elements:-");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
b[i][j]=sc.nextInt();
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
sum[i][j]=a[i][j]+b[i][j];
}
}
System.out.println("Sum of matrix (A) and (B)");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(sum[i][j]+"\t");
}
System.out.println();
}
}
}Java