JAVA Program to add, multiply two Matrix object





class Matrix
{
int m,n;
int ar[][];

Matrix(int a,int b)
{
int i;
m=a;
n=b;
ar=new int[a][];
for(i=0;i<m;i++)
ar[i]=new int[b];
}

void insertData()
{
int i,j,k=1;
for(i=0;i<m;i++)
{
k=1;
for(j=0;j<n;j++)
ar[i][j]=k++;
}
}

Matrix addMat(Matrix ob)
{
int i,j;
Matrix ob1=new Matrix(m,n);
if(m==ob.m && n==ob.n)
{
for(i=0;i<m;i++)
for(j=0;j<n;j++)
ob1.ar[i][j]=ar[i][j]+ob.ar[i][j];
}
else
System.out.println("Condition not matched ");
return ob1;

}


Matrix multiMat(Matrix ob)
{
int i,j,k;
Matrix ob1=new Matrix(m,n);
if(n==ob.m)
{
for(i=0;i<m;i++)
{
for(j=0;j<ob.n;j++)
{
ob1.ar[i][j]=0;
for(k=0;k<n;k++)
ob1.ar[i][j]+=ar[i][k]*ob.ar[k][j];
}

}
}
else
System.out.println("Condition not matched ");
return ob1;

}

void disp()
{
int i,j;


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
System.out.print(ar[i][j]+" ");
System.out.println();
}
}
}


class AddMatrix
{
public static void main(String []r)
{
Matrix ob=new Matrix(4,4);
Matrix ob1=new Matrix(4,4);
Matrix ob2;
ob.insertData();
ob1.insertData();

System.out.println("Matrix 1 : ");
ob.disp();
System.out.println("Matrix 1 : ");
ob1.disp();

ob2=ob.addMat(ob1);
System.out.println("Added Matrix : ");
ob2.disp();
System.out.println("Multiplied Matrix : ");
ob2=ob.multiMat(ob1);
ob2.disp();
}
}



I/O : run this programming and its clear to understand ....

Comments

Popular posts from this blog

Pascal Triangle using 2D array

JAVA program to add two distance