This is a C++ Program to Calculate Dot Product of Two Matrices.
The program takes two matrices and calculates the dot product.
1. The program takes the size of the two matrices.
2. If they are not equal, dot product cannot be found and the program is exited.
3. Else the dot product of the matrices is calculated.
4. The result is printed.
5. Exit.
Here is the source code of C++ Program to Calculate Dot Product of Two Matrices. The program output is shown below.
#include<iostream>
using namespace std;
int main ()
{
int i, j, m, n, p, q;
int A[10][10], B[10][10], C[10];
cout << "Enter number of rows and columns of matrix A : ";
cin >> m >> n;
cout << "Enter number of rows and columns of matrix B : ";
cin >> p >> q;
if ((m != p) && (n != q))
{
cout << "Dot product cannot be found as matrices are not of same size!";
exit(0);
}
cout << "Enter elements of matrix A : ";
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
cin >> A[i][j];
cout << "Enter elements of matrix B : ";
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
cin >> B[i][j];
for (i = 0; i < m; i++)
{
C[i] = 0;
for (j = 0; j < n; j++)
C[i] += A[i][j] * B[i][j];
}
// Printing matrix A //
cout << "Matrix A : \n ";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
cout << A[i][j] << " ";
cout << "\n ";
}
// Printing matrix B //
cout << "Matrix B : \n ";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
cout << B[i][j] << " ";
cout << "\n ";
}
cout << "Dot product : \n ";
for (i = 0; i < m; i++)
cout << C[i] << " ";
return 0;
}
1. The user is asked to enter the number of rows and columns of the two matrices.
2. If the corresponding rows and columns are not equal, then dot product can’t be calculated. The program is exited.
3. Else, elements of both the matrices are asked to enter and stored int the arrays ‘A’ and ‘B’.
4. The corresponding columns of A and B are multiplied and added which gives the dot product of that column as each column is created as a vector.
5. The result is then printed.
Case 1 : Enter number of rows and columns of matrix A : 3 3 Enter number of rows and columns of matrix B : 3 3 Enter elements of matrix A : 1 2 3 4 5 6 7 8 9 Enter elements of matrix B : 9 8 7 6 5 4 3 2 1 Matrix A : 1 2 3 4 5 6 7 8 9 Matrix B : 9 8 7 6 5 4 3 2 1 Dot product : 46 73 46 Case 2 : Enter number of rows and columns of matrix A : 1 3 Enter number of rows and columns of matrix B : 3 1 Dot product cannot be found as matrices are not of same size! Case 3 : Enter number of rows and columns of matrix A : 2 2 Enter number of rows and columns of matrix B : 2 2 Enter elements of matrix A : 10 20 30 40 Enter elements of matrix B : 4 3 2 1 Matrix A : 10 20 30 40 Matrix B : 4 3 2 1 Dot product : 100 100
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Apply for C++ Internship
- Apply for Computer Science Internship
- Check C++ Books
- Check Programming Books
- Check Computer Science Books