Program to display matrix addition, multiplication and transpose in C++
#include<iostream.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,r,co;
clrscr();
cout<<"\nEnter No. of Rows :: ";
cin>>r;
cout<<"\nEnter No. of Columns :: ";
cin>>co;
cout<<"\nEnter First Matrix Elements :";
for(i=0;i<r;i++)
for(j=0;j<co;j++)
{
cout<<"\nEnter Element :: ";
cin>>a[i][j];
}
cout<<"\nEnter Second Matrix Elements :";
for(i=0;i<r;i++)
for(j=0;j<co;j++)
{
cout<<"\nEnter Element :: ";
cin>>b[i][j];
}
for(i=0;i<r;i++) // nested loop for matrix addition
for(j=0;j<co;j++)
c[i][j]=a[i][j]+b[i][j];
cout<<"\n\nFirst Matrix :: \n";
for(i=0;i<r;i++)
{
for(j=0;j<co;j++)
cout<<"\t"<<a[i][j];
cout<<"\n";
}
cout<<"\n\nSecond Matrix :: \n";
for(i=0;i<r;i++)
{
for(j=0;j<co;j++)
cout<<"\t"<<b[i][j];
cout<<"\n";
}
cout<<"\n\nAddition Matrix :: \n";
for(i=0;i<r;i++)
{
for(j=0;j<co;j++)
cout<<"\t"<<c[i][j];
cout<<"\n";
}
if(r==co) // if no. of rows of first matrix is equal to no. of cols of second matrix
{
for(i=0;i<r;i++) // nested loop for matrix multiplication
for(j=0;j<co;j++)
{
c[i][j]=0;
for(k=0;k<co;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
cout<<"\n\nMultiplication Matrix :: \n";
for(i=0;i<r;i++)
{
for(j=0;j<co;j++)
cout<<"\t"<<c[i][j];
cout<<"\n";
}
}
else
cout<<"\n\nMatrix Multiplication not possible.";
for(i=0;i<r;i++) // Loop to find transpose of matrix c
for(j=i;j<co;j++)
if(i!=j)
{
k=c[i][j];
c[i][j]=c[j][i];
c[j][i]=k;
}
cout<<"\n\nTranspose of above Matrix :: \n";
for(i=0;i<co;i++)
{
for(j=0;j<r;j++)
cout<<"\t"<<c[i][j];
cout<<"\n";
}
getch();
}
OUTPUT
Enter No. Of Rows :: 2
Enter No. Of Column :: 2
Enter First Matrix Element :
Enter Element:: 1
Enter Element:: 2
Enter Element:: 3
Enter Element:: 4
Enter Second Matrix Element:
Enter Element:: 1
Enter Element:: 2
Enter Element:: 3
Enter Element:: 4
First Matrix ::
1 2
3 4
Second Matrix ::
1 2
3 4
Addition Matrix ::
2 4
6 8
Multiplication Matrix ::
7 10
15 22
Transpose Of Above Matrix ::
7 15
10 22