Java program for addition of two matrices / two 2-Dimentional arrays
PROGRAM:
import java.util.*;class MatrixAddition{
public static void main(String args[]){
int a[][],b[][],c[][];
a=new int[3][3];
b=new int[3][3];
c=new int[3][3];
int i,j;
Scanner scan=new Scanner(System.in);
System.out.println("Enter elements of matrix A");
for(i=0;i<a.length;i++)
{
for(j=0;j<a[i].length;j++)
{
a[i][j]=scan.nextInt();
}
}
System.out.println("Enter elements of matrix B");
for(i=0;i<b.length;i++)
{
for(j=0;j<b[i].length;j++)
{
b[i][j]=scan.nextInt();
}
}
for(i=0;i<b.length;i++)
{
for(j=0;j<b[i].length;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
System.out.println("Matrix obtained after adding two matrices is:");
for(i=0;i<b.length;i++)
{
for(j=0;j<b[i].length;j++)
{
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
}
OUTPUT:
Enter elements of matrix A10 20 30
40 50 60
70 80 90
Enter elements of matrix B
10 10 10
10 10 10
10 10 10
Matrix obtained after adding two matrices is:
20 30 40
50 60 70
80 90 100