This is a C++ Program to Calculate Dot Product of Two Matrices.

Problem Description

The program takes two matrices and calculates the dot product.

Problem Solution

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.

C++ Program/Source code

Here is the source code of C++ Program to Calculate Dot Product of Two Matrices. The program output is shown below.

#include

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;
}
Runtime Test Cases
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