Google News
logo
C++ Program to Multiply Two Matrix Using Multi-dimensional Arrays
In the following example of C++ program that multiplies two matrices using multi-dimensional arrays :
Program :
#include <iostream>
using namespace std;

const int MAX = 10;

int main() {
   int matrix1[MAX][MAX], matrix2[MAX][MAX], product[MAX][MAX];
   int rows1, cols1, rows2, cols2, i, j, k;

   cout << "Enter number of rows and columns of matrix1: ";
   cin >> rows1 >> cols1;

   cout << "Enter elements of matrix1:" << endl;

   for(i=0; i<rows1; i++) {
      for(j=0; j<cols1; j++) {
         cin >> matrix1[i][j];
      }
   }

   cout << "Enter number of rows and columns of matrix2: ";
   cin >> rows2 >> cols2;

   if(cols1 != rows2) {
      cout << "Matrix multiplication not possible.";
      return 0;
   }

   cout << "Enter elements of matrix2:" << endl;

   for(i=0; i<rows2; i++) {
      for(j=0; j<cols2; j++) {
         cin >> matrix2[i][j];
      }
   }

   for(i=0; i<rows1; i++) {
      for(j=0; j<cols2; j++) {
         product[i][j] = 0;
         for(k=0; k<cols1; k++) {
            product[i][j] += matrix1[i][k] * matrix2[k][j];
         }
      }
   }

   cout << "Product of matrices:" << endl;

   for(i=0; i<rows1; i++) {
      for(j=0; j<cols2; j++) {
         cout << product[i][j] << " ";
      }
      cout << endl;
   }

   return 0;
}


* In this program, we declare three 2D arrays matrix1, matrix2, and product of size MAX x MAX. We also declare variables for the number of rows and columns in both matrices.

* We then take input from the user for the elements of both matrices using nested for loops.

* We check if the multiplication is possible or not by comparing the number of columns in matrix1 with the number of rows in matrix2.

* Next, we multiply the two matrices using nested for loops. We also use an additional loop for the summation of the product of corresponding elements of the two matrices.

* Finally, we print the product matrix using nested for loops.

Output :
Enter number of rows and columns of matrix1: 2 3
Enter elements of matrix1:
5 8 1
3 6 7
Enter number of rows and columns of matrix2: 3 2
Enter elements of matrix2:
2 7
5 9
3 5
Product of matrices:
53 112 
57 110