Matrix addition means addition of respective positions. That is, element of 0th row 0th column of first matrix will be added with 0th row and 0th column of second matrix and placed in resultant matrix at 0th row and 0th column position. And this way all the element positions of first matrix are added with the respective positions of second matrix and stored in resultant matrix at the same position.
import java.io.*;
class AddMatrix
{
public static void main(String args[])
throws IOException
{
BufferedReader k=new BufferedReader(new InputStreamReader(System.in));
int m1[][]=new int[3][3];
int m2[][]=new int[3][3];
int m3[][]=new int[3][3];
int i,j;
String m;
System.out.println("Enter Elements of First Matrix of Order 3 x 3");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
m=k.readLine();
m1[i][j]=Integer.parseInt(m);
}
}
System.out.println("Enter Elements of Second Matrix of Order 3 x 3");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
m=k.readLine();
m2[i][j]=Integer.parseInt(m);
}
}
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
m3[i][j]=m1[i][j]+m2[i][j];
}
}
System.out.println("The First Matrix Entered is ");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
System.out.print(m1[i][j]+"\t");
}
System.out.println();
}
System.out.println("The Second Matrix Entered is ");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
System.out.print(m2[i][j]+"\t");
}
System.out.println();
}
System.out.println("The Addition of Matrix is ");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
System.out.print(m3[i][j]+"\t");
}
System.out.println();
}
}
}
One of the another Example we can see.
import java.io.*;
class matrix
{
int h[][]=new int[3][3];
void setmat() throws IOException
{
int i,j;
BufferedReader gg=new BufferedReader(new InputStreamReader(System.in));
String m;
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
m=gg.readLine();
h[i][j]=Integer.parseInt(m);
}
}
}
void showmat()
{
int i,j;
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
System.out.print(h[i][j]+"\t");
}
System.out.println();
}
}
void addmat(matrix u, matrix v)
{
int i,j;
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
h[i][j]=u.h[i][j]+v.h[i][j];
}
}
}
};
class mataddclass
{
public static void main(String args[])
{
matrix ml=new matrix();
matrix m2=new matrix();
matrix m3=new matrix();
System.out.println("Enter elements for matrix l of order 3x3:");
try
{
ml.setmat();
}
catch(IOException e){}
System.out.println("Enter elements for matrix 2 of order 3x3:");
try
{
m2.setmat();
}
catch(IOException e){}
m3.addmat(ml,m2);
System.out.println("Elements of first matrix are ");
ml.showmat();
System.out.println("Elements of second matrix are ");
m2.showmat();
System.out.println("Addition of matrices are ");
m3.showmat();
}
}