# C++ and Python Program to Calculate 3X3 Matrix Multiplication

Posted in

Vinay Khatri
Last updated on December 11, 2022

In this blog, we will write code to calculate 3x3 matrix multiplication. A matrix is a 2D array, which means it is a list inside a list. To multiply two matrices, their dimensions should be the same. For this tutorial, we require square matrices.

A matrix is known as a square matrix when its number of rows is equal to the number of columns.

We will create two programs here, one in C++ and the other in the Python programming language. Each of the programs will ask the user to enter the elements for two 3x3 matrices. Each matrix will have 9 elements. The program then multiplies the two matrices and prints the resultant matrix.

## How to Calculate 3x3 Matrix Multiplication?

### C++ Program to Calculate 3x3 Matrix Multiplication

``````#include<iostream.h>
#include< conio.h>
#include<stdio.h>
#include<math.h>
void main()
{
clrscr();
int arr1[3][3],arr2[3][3],arr3[3][3];
cout<<"Enter the Elements of Array 1: "<<endl;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
cin>>arr1[i][j];
}
cout<<"Enter the Elements of Array2:"<<endl;
for(i=0;i<3;i++)
{for(int j=0;j<3;j++)
cin>>arr2[i][j];
}
for(i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{arr3[i][j]=0;
for(int k=0;k<3;k++)
arr3[i][j]=arr3[i][j]+(arr1[i][k]*arr2[k][j]);
cout<<arr3[i][j]<<" ";
}
cout<<endl;
}
getch();
}``````

Output:

``````Enter the Elements of Array 1:

2
4
5
6
3
2
4
7
3

Enter the Elements of Array 2:

1
3
4
6
8
6
4
2
6

46 48 62
32 46 54
58 74 76``````

### Python Program to Calculate 3x3 Matrix Multiplication

``````arr1=[[0,0,0],[0,0,0],[0,0,0]]
arr2=[[0,0,0],[0,0,0],[0,0,0]]
arr3= [[0,0,0],[0,0,0],[0,0,0]]

print("Enter the Elements of Array 1:")
for i in range(0,3):
for j in range(0,3):
element= int(input())
arr1[i][j]=element

print("Enter the Elements of Array 2:")
for i in range(3):
for j in range(3):
element2= int(input())
arr2[i][j]=element2

for i in range(3):
for j in range(3):
for k in range(3):
arr3[i][j]+=arr1[i][k]*arr2[k][j]

print(arr3[0],'\n',arr3[1],'\n',arr3[2])``````

Output:

``````Enter the Elements of Array 1:

3
4
5
2
54
6
23
45
12

Enter the Elements of Array 2:

23
34
54
5
76
65
34
76
85
[259, 786, 847]
[520, 4628, 4128]
[1162, 5114, 5187]``````

## Conclusion

Matrix multiplication is a common endeavor in scientific and mathematical programming. Hence, every programmer must be aware of it. In this tutorial, we have provided code that is capable of multiplying only a 3x3 matrix. To learn the concept better, you can design the program for other square matrices, like 4x4 and 5x5 matrices.

Moreover, you can create a program that can multiply square matrices of any size. However, doing so will require much knowledge and effort. Let us know if you are able to do so.