Rule : Let say we have two matrices A , B both having n rows and m columns.Multiplication of two matrices is only possible if number of columns in Matrix A is equal to number of rows in Matrix B.Otherwise multiplication is not possible.So careful of that.
Lets write a program for it using C++ Programming Language.If you want to know learn C++ programming go step by step. There are comments as well. You can easily understand if you follow the comments.
For comments i used // and /**/
// ==> used for comments of one line
Program code:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int a[10][10],b[10][10] ,c[10][10] ; // arrays
int n , m , p ,q ; // n = number of rows , m = no.of coloumns
// p = number of rows , q = no.of coloumns
int x[10] ;
cout<< "Enter number of rows for matrix A"<<endl<<endl ;
cin>> n ;
cout<<"Enter number of coloumns for matrix a"<<endl<<endl ;
cin>> m ;
cout<<"Enter number of rows for matrix b"<<endl<<endl;
cin>>p;
cout<<"Enter number of coloumns for matrix b"<<endl<<endl;
cin>>q;
if(m==p) /* condition of multiplication */
{
/* Code for first matrix A */
cout<<endl;
cout<<"Enter element for matrix A "<<endl;
for(int i = 1; i<= n ;i++)
{
for(int j = 1; j <= m; j++)
{
cin>> a[i][j];
}
}
cout<<endl<<endl;
cout<< "First matrix A is = "<<endl;
for(int i = 1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
/* Code for Second matrix B */
cout<<endl<<endl;
cout<<"Enter elements for Second matrix B "<<endl;
for( int i=1; i<=p;i++)
{
for(int j =1; j<= q; j++)
{
cin>>b[i][j];
}
}
cout<<endl<<endl;
cout<<"Second matrix B is = " << endl;
for(int i = 1;i<=p;i++)
{
for(int j=1; j<=q ; j++)
{
cout<<b[i][j]<< " ";
}
cout<<endl;
}
/* code for multiplicaton */
for(int i = 1; i <= m ; i++)
{
for(int j = 1; j<= p ;j++)
{
c[i][j] = 0;
for(int k = 1; k<=m ;k++)
{
x[k]=0;
x[k]=a[i][k] * b[k][j];
c[i][j]=c[i][j] + x[k] ;
}
}
}
cout<<endl<<endl;
cout<<"Multiplication of two matrix A and matrix B is " <<endl<<endl;
for(int i= 1;i<=n ;i++)
{
for(int j=1;j<=q;j++)
{
cout<<c[i][j]<<" ";
}
cout<<endl;
}
}
else
cout<<"multiplication is not possible";
getch();
}
Output: After executing and compiling , the result is
Hope that you will find this helpful.
No comments:
Post a Comment