C++ Program to Multiply Two Matrix Using Multi-dimensional Arrays

In this tutorial, we will learn and write a C++ program to print the multiplication of two matrices. Before that, you may go through the following topics in C++ programming:

The program takes the user input for the number of rows and columns and then the elements for both the matrices.


C++ Program to Multiply Two Matrix Using Multi-dimensional Arrays

Multiplication of matrix in C++.

#include <iostream>
using namespace std;
int main()
{
  int a[10][10], b[10][10], mul[10][10];
  int row, col, i, j, k;
  
  cout << "Enter the no. of rows: ";
  cin >> row;
  cout << "Enter the no. of columns: ";
  cin >> col;
  
  // 1st matrix user input
  cout << endl << "Enter 1st Matrix elements: " << endl;
  for (i = 0; i < row; i++)
  {
    for (j = 0; j < col; j++)
      cin >> a[i][j];
  }

  // 2nd matrix user input
  cout << endl << "Enter 2nd Matrix elements: " << endl;
  for (i = 0; i < row; i++)
  {
    for (j = 0; j < col; j++)
      cin >> b[i][j];
    
  }
  
 // matrix multiplication
  for (i = 0; i < row; i++)
  {
    for (j = 0; j < col; j++)
    {
      mul[i][j] = 0;
      for (k = 0; k < col; k++)
        mul[i][j] += a[i][k] *b[k][j];
      
    }
  }

 //Displaying the result
  cout << "Multiplication of matrix" << endl;   
  for (i = 0; i < row; i++)
  {
    for (j = 0; j < col; j++)
      cout << mul[i][j] << " ";

    cout << "\n";
  }

  return 0;
}

Output:

Enter the no. of rows: 3
Enter the no. of columns: 3

Enter 1st Matrix elements:
2 3 6
2 3 6
2 3 6

Enter 2nd Matrix elements:
1 2 3
1 2 3
1 2 3
Multiplication of matrix
11 22 33
11 22 33
11 22 33