Write a C++ program to demonstrate exception handling by using example of multiplication of two matrices.
Answers
#include <iostream>
using namespace std;
int main()
{
cout<<"*** EXCEPTION HANDLING IN MULTIPLICATION OF TWO MATRICES ***"<<endl<<endl;
int row, column, x, y;
cout<<"Dimensions for first matrix"<<endl;
cout<<"Row : ";
cin>>x;
cout<<"Column : ";
cin>>column;
cout<<"Dimensions for second matrix"<<endl;
cout<<"Row : ";
cin>>row;
cout<<"Column : ";
cin>>y;
try
{
if(column != row)
{
throw 99;
}
}
catch(int)
{
cout<<endl<<"Error 521 : Error in dimensions. The matrices cannot be multiplied."<<endl;
cout<<"Hint : To multiply two matrices, the number of columns of the first matrix must be equal to the number of rows of the second matrix."<<endl<<endl;</endl<<
return 0;
}
int a[x][column], b[row][y], c[x][y], i, j, k;
cout<<"\nEnter the first matrix"<<endl;
for(i=0 ; ii++)
{
for(j=0 ; j<column ; j++)
{
cin>>a[i][j];
}
}
cout<<"\nEnter the second matrix"<<endl;
for(i=0 ; ii++)
{
for(j=0 ; j<y ; j++)
{
cin>>b[i][j];
}
}
for(i=0 ; ii++)
{
for(j=0 ; j<y ; j++)
{
c[i][j] = 0;
}
}
for(i=0 ; i<x ; i++)
{
for(j=0 ; j<y ; j++)
{
for(k=0 ; k<column ; k++)
{
c[i][j] += (a[i][k] * b[k][j]);
}
}
}
cout<<"\nThe multiplication of both the matrices are :"<<endl;
for(i=0 ; i<x ; i++)
{
for(j=0 ; j<y ; j++)
{
cout<<c[i][j]<<"\t";
}
cout<<endl;
}
return 0;
}