# C++ Program to Multiply Two Matrices

## C++ Program to Multiply Two Matrices

A matrix is a rectangular array of numbers that is arranged in the form of rows and columns. A 2*2 matrix has 2 rows and 2 columns, A 3*3 matrix has 3 rows and 3 columns.
To write matrices program in C++ we need receive two matrices value from user after this process we start multiplying the two matrices and store the multiplication result inside any variable and finally store the value of sum in the third matrix say mat3[ ][ ].

To understand below example, you have must knowledge of following C++ programming topics; For Loop in C++ and Array in C++.

### Examples to C++ Program to Multiply Two Matrices

The below program multiplies two square matrices of size 4*4

## Example

```Input : Matrices_1[][] = {{1, 2},
{3, 4}}
Matrices_2[][] = {{1, 1},
{1, 1}}
Output : {{3, 3},
{7, 7}}
Input : Matrices_1[][] = {{2, 4},
{3, 4}}
Matrices_2[][] = {{1, 2},
{1, 3}}
Output : {{6, 16},
{7, 18}}
```

To understand below example, you have must knowledge of following C++ programming topics; String in C++, for looping statements we need know For Loop in C++ and Array in C++.

## Program to Multiply 2X2 Matrices in C++

```#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
int mat1[2][2], mat2[2][2], mat3[2][2], sum=0, i, j, k;
cout<<"Enter First Matrix Element (2*2): ";
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
cin>>mat1[i][j];
}
}
cout<<"Enter Second Matrix Element (2*2): ";
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
cin>>mat2[i][j];
}
}
cout<<"Multiplying two Matrices........\n";
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
sum=0;
for(k=0; k<2; k++)
{
sum = sum + mat1[i][k] * mat2[k][j];
}
mat3[i][j] = sum;
}
}
cout<<"\nMultiplication of Two Matrices : \n";
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
cout<<mat3[i][j]<<" ";
}
cout<<"\n";
}
getch();
}
```

## Output

```Enter First Matrix Element (2*2): 2
3
4
1
Enter Second Matrix Element (2*2): 7
4
3
5

Multiplying two Matrices........
Multiplication of Two Matrices
23 23
31 21
```

## Program to Multiply 3X3 Matrices in C++

```#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
int mat1[3][3], mat2[3][3], mat3[3][3], sum=0, i, j, k;
cout<<"Enter First Matrix Element (3*3): ";
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
cin>>mat1[i][j];
}
}
cout<<"Enter Second Matrix Element (3*3): ";
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
cin>>mat2[i][j];
}
}
cout<<"Multiplying two Matrices........\n";
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
sum=0;
for(k=0; k<3; k++)
{
sum = sum + mat1[i][k] * mat2[k][j];
}
mat3[i][j] = sum;
}
}
cout<<"\nMultiplication of Two Matrices : \n";
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
cout<<mat3[i][j]<<" ";
}
cout<<"\n";
}
getch();
}
```

## Output

```Enter First Matrix Element (3*3): 3
2
1
4
3
5
6
3
2

Enter Second Matrix Element (3*3): 3
2
4
5
2
1
6
7
3

Multiplying two Matrices........
Multiplication of Two Matrices
25 17 17
57 49 34
45 32 33
```