Saturday 17 September 2011

Matrix class using default argument,static data members and friend function


Matrix class using default argument,static data members and friend function
Aim:
To write a C++ program to perform matrix manipulation using static variable, default argument and friend function.
Algorithm:
Step 1: Declare the class as Matrix.
Step 2: Declare the data member as r, c and **x.
Step 3: Declare the member function as
Matrix(int r1=2,int c1=2);
void get();
void put();
friend Matrix add(Matrix,Matrix);
friend Matrix mul(Matrix,Matrix);
Step 4: Member function with default argument is used to initialize the value of the
matrix.
Step 5: get() function is used to get the values of two matrices.
Step 6: add() and mul() function are used to perform addition and multiplication of the
matrices.
Step 7: In the main, create objects A and B for the Matrix class.
Step 8: Call the get() method to get the value of matrix A and B.
Step 9: Call the add() and mul() method to perform the particular operation and finally
display the result.
Program:
#include<stdio.h>
#include<conio.h>
#include<iomanip.h>

class matrix
{
static int r,c;
int**x;
public:
matrix(int r1=2,int c1=2);
void get();
void put();
friend matrix add(matrix,matrix);
friend matrix mul(matrix,matrix);
};

matrix::matrix(int r1,int c1)
{
r=r1;c=c1;
x=new int*[r];
for(int i=0;i<r;i++)
x[i]=new int[c];
for(i=0;i<r;i++)
for(int j=0;j<c;j++)
{
x[i][j]=0;
}
}

void matrix::get()
{
cout<<"\n enter the matrix of size"<<r<<"x"<<c<<endl;
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
cin>>x[i][j];
}

void matrix::put()
{

for(int i=0;i<r;i++,cout<<endl)
for(int j=0;j<c;j++)
cout<<setw(4)<<x[i][j];
}
int matrix::r;
int matrix::c;

matrix add(matrix a,matrix b)
{
matrix c;
for(int i=0;i<a.r;i++)
for(int j=0;j<a.c;j++)
c.x[i][j]=a.x[i][j]+(b.x[i][j]);
return c;
}

matrix mul(matrix a,matrix b)
{
matrix c;
for(int i=0;i<a.r;i++)
for(int j=0;j<b.c;j++)
for(int k=0;k<a.c;k++)
{
c.x[i][j]=c.x[i][j]+a.x[i][k]*(b.x[k][j]);
}
return c;
}

void main()
{
clrscr();
matrix a,b,c1,d1;
a.get();
b.get();
cout<<"The matrix A:"<<endl;
a.put();
cout<<"The matrix B:"<<endl;
b.put();
c1=add(a,b);
cout<<"The resultant matrix (A+B):"<<endl;
c1.put();
cout<<"\n\n The resultant matrix(A*B):"<<endl;
d1=mul(a,b);
d1.put();
getch();
}

Output:

Enter the matrix of size2x2
2 3
2 3

Enter the matrix of size2x2
4 5
4 5

The matrix A:
2   3
2   3

The matrix B:
   4   5
   4   5

The resultant matrix(A+B):
   6   8
   6   8

The resultant matrix(A*B):
  20  25
  20  25

0 comments:

Post a Comment