Matrix multiplication using cpp language


/*Md. Alamgir Hossain
Dept. of Computer Science & Engineering
Jessore University of Science & Technology

*/

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int m,n,p,q;
    int first[100][100];
    int second[100][100];
    int res[100][100];

    cout<<"Enter first Matrix row and column number : ";
    cin>>m>>n;
    cout<<"\nEnter second Matrix row and column number : ";
    cin>>p>>q;

    if(n!=p){
        cout<<"\nMultiplication is Not possible. Try again with valid row and column number........"<<endl;
    }
    else{
        cout<<"\nMultiplication possible..........."<<endl;
        cout<<"\nEnter first Matrix values : \n";
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                cin>>first[i][j];
            }
        }
        cout<<"\nEnter second Matrix values : \n";
        for(int i=0;i<p;i++){
            for(int j=0;j<q;j++){
                cin>>second[i][j];
            }
        }
        int sum=0;
        for(int i=0;i<m;i++){
            for(int j=0;j<q;j++){
                for(int k=0;k<p;k++){
                    sum=sum+first[i][k]*second[k][j];
                }
                res[i][j]=sum;
                sum=0;
            }
        }
        cout<<"\nResult matrix is : "<<endl;
        for(int i=0;i<m;i++){
            for(int j=0;j<q;j++){
                cout<<res[i][j]<<"\t";
            }
            cout<<endl;
        }
    }
    return 0;
}
/*
Enter first Matrix row and column number : 2 2

Enter second Matrix row and column number : 2 2
Multiplication possible...........

Enter first Matrix values :
4 5
7 8

Enter second Matrix values :
3 5
6 8

Result matrix is :
42      60
69      99

*/

No comments:

Post a Comment