-->





Translate

Matrices Multiplication in C++ Code Tutorial

Leave a Comment
Write a simple c++ program to multiply two matrices using 2D arrays. Use any compiler turbo c, visual studio or codeblocks compiler.

Program Explanation:

  • Here is the simple example for beginners to understand the basic working of 2Dimensional arrays.
  • Program is very simple it takes input in two 2D arrays each with size of 2X2. 
  • After taking the input program multiply two matrix in 3 nested for loops.
  • Size of arrays is defined using "const int variables" Note: if we do not use const here there will be error because array size needs constant value in square brackets e.g.  array[const value]
Program code:
Compiler used: CodeBlocks C++ Compiler

#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<<"\n\n\nEnter 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<<"\n\n\t\tResultant Matrix:"<<endl;

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






Example input/output
c++ program to calculate matrix multiplication using 2D arrays
This program is very helpful for beginners it can be a complex by adding a matrix multiplication rule.
It is recommended to run this code and add the condition where number of colums of first matrix should be equal than the number of rows of second matrix.
For another example : matrices addition code here

0 comments:

Post a Comment