C++ Program to do operation on matrices
This is done in Code::Blocks Ide. Some modification are needed to run in Turbo C++ ide, like changing header into iostream.h, adding one more header conio.h and hence getch at the end of the program, removing using namespace std;, and all
#include<iostream>
#include<stdlib.h>
using namespace std;
class matrix
{
int fraw,fcol,sraw,scol,i,j,k;
int f[50][50],s[50][50],l[50][50];
public:
void input()
{
cout<<"Enter number of raws and columns do you want for fisrt matrix\n";
cin>>fraw>>fcol;
cout<<"Enter number of raws(same as number of columns in first) and columns of second matrix\n";
cin>>sraw>>scol;
cout<<"Enter "<<fraw*fcol<<"elements of first matrix\n";
for(i=0;i<fraw;i++)
{
for(j=0;j<fcol;j++)
{
cin>>f[i][j];
}
}
cout<<"Enter "<<sraw*scol<<"elements of second matrix\n";
for(i=0;i<sraw;i++)
{
for(j=0;j<scol;j++)
{
cin>>s[i][j];
}
}
}
void addition()
{
cout<<"Sum of two matrices\n";
for(i=0;i<fraw;i++)
{
for(j=0;j<fcol;j++)
{
l[i][j]=f[i][j]+s[i][j];
cout<<"\t"<<l[i][j];
}
cout<<"\n";
}
}
void substraction()
{
cout<<"Difference of two matrices\n";
for(i=0;i<fraw;i++)
{
for(j=0;j<fcol;j++)
{
l[i][j]=f[i][j]-s[i][j];
cout<<"\t"<<l[i][j];
}
cout<<"\n";
}
}
void multiplication()
{
if(fcol!=sraw)
cout<<"No of columns of First matrix and raws of second matrix is not same, multiplication is not allowed";
else
{
for(i=0;i<fraw;i++)
for (j=0;j<scol;j++)
{
l[i][j]=0;
}
for(i=0;i<fraw;i++)
for (j=0;j<scol;j++)
for (k=0;k<fcol;k++)
{
l[i][j]=l[i][j]+f[i][k]*s[k][j];
}
for(i=0;i<fraw;i++)
{
for (j=0;j<scol;j++)
{
cout<<l[i][j]<<"\t";
}
cout<<"\n";
}
}
}
void read()
{
cout<<"Elements of first matrix\n";
for(i=0;i<fraw;i++)
{
for(j=0;j<fcol;j++)
{
cout<<f[i][j]<<"\t";
}
cout<<"\n";
}
cout<<"Elements of second matrix\n";
for(i=0;i<sraw;i++)
{
for(j=0;j<scol;j++)
{
cout<<s[i][j]<<"\t";
}
cout<<"\n";
}
};
};
int main()
{
int c;
char an;
matrix a;
a.input();
do
{
cout<<"Choose from the following options:\n";
cout<<"1 Addition\t\t2 Subtraction\n";
cout<<"3 Multiplication\t4 Reading\n";
cout<<"5 Exit";
cin>>c;
switch (c)
{
case 1:
a.addition();
break;
case 2:
a.substraction();
break;
case 3:
a.multiplication();
break;
case 4:
a.read();
break;
default:
exit(0);
}
cout<<"Do you want to continue: y/n";
cin>>an;
}
while(an=='y'||an=='Y');
return 0;
}