Matrix multiplication in C++

How matrix multiplication in C++ Works:

 
  • Input two matrices.
  • Run 3 for loops (i,j,k).
  • Multiplication will be addition of First_Matrix[i][k]*Second_Matrix[k][j] for each element.
  • Resultant matrix is stored in third Matrix.

 

CODE:

#include<iostream>
using namespace std;
int main(){
//Using const int for array size
    const int row=2,col=2;
// if not use const error found
cout<<"Size of Matrices : "<<row<<" X "<<col<<endl;
cout<<"Enter Value For FirstMatrix Matrix:"<<endl;

    int firstMatrix[row][col];
    int secondMatrix[row][col];
    int resultantMatrix[row][col], var;

int i,j;
    for( i=0;i<row;i++){
        cout<<"Enter value for row number: "<<i+1<<endl;
        for( j=0;j<col;j++){
            cin>>firstMatrix[i][j];
        }
    }
cout<<"nnnEnter Value For SecondMatrix Matrix:"<<endl;
    for( i=0;i<row;i++){
        cout<<"Enter value for row number: "<<i+1<<endl;
        for( j=0;j<col;j++){
            cin>>secondMatrix[i][j];
        }
    }
var=0;
        // ResultantMatrixant Matrix
        for( i=0;i<row;i++){
            for( j=0;j<col;j++){
                for(int k=0;k<row;k++){
                   var=var+(firstMatrix[i][k]*secondMatrix[k][j]);
                   cout<<var<<endl;
                    }
                 resultantMatrix[i][j]=var;
                 var=0;
            }
        }
cout<<"nnttResultant Matrix:"<<endl;

    for( i=0;i<row;i++){
        cout<< endl;
        for( j=0;j<col;j++){
            cout<<"tt"<<resultantMatrix[i][j]<<"    ";
        }
    }
return 0;
}

 

Leave a Reply