Question
Program to calculate the addition of 2 matrices
Matrix a = [1, 1, 1]
[4, 5, 6]
[1, 2, 3]
matrix b = [1, 1, 1]
[-2, 3, 1]
[1, 0, 1]
Addition of two matrices:
[2 2 2]
[2 8 7]
[2 2 4]
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class SumOfTwoMatrix
{
public static void main(String[] args)
{
int row=0, col=0,i=0,j=0;
int a[][],b[][],sum[][];
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE ROW OF MATRIX");
row=sc.nextInt();
System.out.println("ENTER THE COLUMN OF MATRIX");
col=sc.nextInt();
a=new int[row][col];
b=new int[row][col];
System.out.println("ENTER THE ELEMENTS IN MATRIX A");
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
a[i][j]=sc.nextInt();
}
}
System.out.println("ENTER THE ELEMENTS IN MATRIX B");
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
b[i][j]=sc.nextInt();
}
}
sum=new int [row][col];
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
sum[i][j]=a[i][j]+b[i][j];
}
}
System.out.println("MATRIX A + MATRIX B");
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
System.out.print(sum[i][j]+" ");
}
System.out.println();
}
}
}