Wednesday 12 October 2011

MATRIX MULTIPLICATION USING FRIEND FUNCTIONS


MATRIX MULTIPLICATION USING FRIEND FUNCTIONS

AIM:
To write a program for matrix multiplication using friend functions using C++.

ALGORITHM:

Step 1: Start the program.
Step 2: Create a class Matrix with two matrix array as data member and a function as their member function.
Step 3: Declare a function multiply as a friend function for the class matrix.get the value of the given two matrix using a member function.
Step 4: Calculate the matrix multiplication using friend function. The friend function is called in the main function without the help of the object and object as its arguments.
Step 5: Display the resultant matrix.
Step 6: Stop the program.

PROGRAM

#include<iostream.h>
#include<conio.h>
class matrix
{
int a[5][5],b[5][5],d[5][5];
int i,j,k,l,m,r,c;
public:
void get();
friend void multiply(matrix m1);
};
void matrix::get()
{
cout<<"\n Enter the dimension (n*m) of the first matrix:";
cin>>r>>c;
cout<<"\n Enter "<< r*c <<" element:";
for(i=0;i<r;i++)
{
 for(j=0;j<c;j++)
 {
  cin>>a[i][j];
 }
}
cout<<"\n The value of the first matrix:";
for(i=0;i<r;i++)
{
cout<<"\n";
for(j=0;j<c;j++)
{
cout<<a[i][j]<<"\t";
}
}
}
void multiply(matrix m1)
{
int i,j,k;
char ch='y';
do
{
cout<<"\n Enter the dimension (n*m) for the second matrix:";
cin>>m1.l>>m1.m;
cout<<"\n Enter "<< m1.l*m1.m <<" element:";
for(i=0;i<m1.l;i++)
{
 for(j=0;j<m1.m;j++)
 {
  cin>>m1.b[i][j];
 }
}
cout<<"\n The value of the second matrix:";
for(i=0;i<m1.l;i++)
{
cout<<"\n";
for(j=0;j<m1.m;j++)
{
cout<<m1.b[i][j]<<"\t";
}
}
if(m1.r==m1.m)
{
for(i=0;i<m1.l;i++)
{
 for(j=0;j<m1.m;j++)
 {
  m1.d[i][j]=0;
  for(k=0;k<m1.m;k++)
  m1.d[i][j]=m1.a[i][k]*m1.b[k][j]+m1.d[i][j];
 }
}
cout<<"\n Resultant Matrix:";
for(i=0;i<m1.l;i++)
{
 cout<<"\n";
 for(j=0;j<m1.m;j++)
 cout<<m1.d[i][j]<<"\t";
 }
}
else
cout<<"\n Rows and Columns are inequal; Muliplication is not possible";
cout<<"\n Do you want to multiply one more matrix:";
cin>>ch;
}
while(ch=='y');
}
void main()
{
clrscr();
matrix m1;
m1.get();
multiply(m1);
getch();
}


OUTPUT:

 Enter the dimension (n*m) of the first matrix: 2 2

 Enter 4 element:1 2 3 4

 The value of the first matrix:
1       2
3       4
 Enter the dimension (n*m) for the second matrix: 2 2

 Enter 4 element:4 5 6 7

 The value of the second matrix:
4       5
6       7
 Resultant Matrix:
16      19
36      43
 Do you want to multiply one more matrix: n



RESULT:
Thus the program for matrix multiplication using friend functions was written and executed.

0 comments:

Post a Comment