# C++ Matrix Multiplication Sample Code

Created By: Debasis Das (6-Feb-2016)

```
//  main.cpp
//  MatrixMultiplications
//  Created by Debasis Das on 05/02/16.

#include <iostream>
#include <stdlib.h>

using namespace std;

int main(int argc, const char * argv[]) {

std::cout << "Hello, World!\n";

int a = {
{0, 1, 2, 3} ,
{4, 5, 6, 7} ,
{8, 9, 10, 11}
};

int b = {
{0, 1, 2} ,
{4, 5, 6} ,
{4, 5, 6} ,
{8, 9, 11}
};

int a_rows = sizeof(a)/sizeof(a);
int a_cols = sizeof(a)/sizeof(a);
cout << "Number of rows in array a = "<< a_rows << "\n";
cout << "Number of cols in array a = "<<  a_cols<< "\n";

int b_rows = sizeof(b)/sizeof(b);
int b_cols = sizeof(b)/sizeof(b);
cout << "Number of rows in array b = "<<  b_rows << "\n";
cout << "Number of cols in array b = "<<  b_cols << "\n";

if (a_cols == b_rows){
cout << "\nThe number of cols in the first array is same as the number of rows in the second array, \nThe multiplication is possible\n";
//initialize the final array
int c[a_rows][b_cols];
int i, j,k;
for (i=0;i<a_rows; i++){
for (j=0;j<b_cols;j++){
c[i][j]=0;
for (k=0;k<b_rows;k++){
c[i][j] = c[i][j]+a[i][k]*b[k][j];
}
}
}
cout << "\nthe final array has been created\n\n";
cout << "time to see the results \n";

for(i=0;i<a_rows;i++)
{
for(j=0;j<b_cols;j++)
{
cout<<"\t"<<c[i][j];
}
cout<<"\n\n";
}
}
else{
cout << "Multiplication of the two array is not possible";
}
return 0;
}
```

Output of the sample code

```Hello, World!
Number of rows in array a = 3
Number of cols in array a = 4
Number of rows in array b = 4
Number of cols in array b = 3

The number of cols in the first array is same as the number of rows in the second array,
The multiplication is possible

the final array has been created

time to see the results
36	42	51

100	122	151

164	202	251

Program ended with exit code: 0
```
Posted in C++ Tagged with: , ,
###### One comment on “C++ Matrix Multiplication Sample Code”
1. www.oneclay.net says:

This program displays the error until the number of columns of first matrix is equal to the number of rows of second matrix.