Matrix Addition Using Array

The following java program is to add two matrices using array.It is also an example of two dimensional array.

import java.io.*;
class MatAdd
{
int m[][],r,c,i,j;
BufferedReader br;
void get(int p,int q)throws Exception
{
br=new BufferedReader(new InputStreamReader(System.in));
r=p;
c=q;
m=new int[r][c];
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
System.out.println("Enter element");
m[i][j]=Integer.parseInt(br.readLine());
}
}
void pro(MatAdd a,MatAdd b)
{
r=a.r;
c=a.c;
m=new int[r][c];
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
m[i][j]=a.m[i][j]+b.m[i][j];
}
}
void show()
{
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
System.out.print("\t"+m[i][j]);
System.out.println("");
}
}
}
class MatAddMain
{
public static void main(String arg[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter r1,c1,r2,c2");
int r1=Integer.parseInt(br.readLine());
int c1=Integer.parseInt(br.readLine());
int r2=Integer.parseInt(br.readLine());
int c2=Integer.parseInt(br.readLine());
if(r1==r2 && c1==c2)
{
MatAdd a=new MatAdd();
MatAdd b=new MatAdd();
MatAdd c= new MatAdd();
a.get(r1,c1);
b.get(r2,c2);
c.pro(a,b);
c.show();
}else
System.out.println("Matrix addition not possible");
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *