Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to multiply two matrix

C++ Code Example — Array Programs

ADVERTISEMENT

WAP to multiply two matrix

Objective

Write a C++ program to multiply two matrices.

Algorithm / Approach

  1. Declare m1 as 3x2, m2 as 2x4, and the result m3 as 3x4.
  2. Use THREE nested loops (i for M1 rows, j for M2 cols, k for the common inner dimension).
  3. Calculate the dot product for each cell: sum = sum + m1[i][k] * m2[k][j].
  4. Assign the sum to m3[i][j] and reset sum = 0.
  5. Print the final product matrix.
main.cpp
#include<iostream>
using namespace std;
int main() {
 int r1 = 3, c1= 2, r2 = 2;
 int c2 = 4,sum =0;
 int m1[3][2],m2[2][4],m3[3][4];
 cout<<"Enter Elements of Mat1: \n";
 for(int i = 0; i< r1; i++) {
  for(int j = 0; j< c1; j++) {
   cin>>m1[i][j];
  }
 }
 cout<<"Enter Elements of Mat2: \n";
 for(int i = 0; i< r2; i++) {
  for(int j = 0; j< c2; j++) {
   cin>>m2[i][j];
  }
 }
 for(int i = 0; i< r1; i++) {
  for(int j = 0; j< c2; j++) {
   for(int k = 0; k< r2;k++) {
    sum = sum+m1[i][k]*m2[k][j];
   }
  m3[i][j]= sum;
  sum = 0;
  }
 }
 cout<<"Product of matrix: \n";
 for(int i = 0; i< r2; i++) {
  for(int j = 0; j< c2; j++) {
   cout<< m3[i][j]<<"  ";
  }
  cout<< endl;
 }
 return 0;
}

Expected Output

Enter Elements of Mat1:
1 3
3 4
2 3
Enter Elements of Mat2:
1 2 3 4
3 4 5 6
Product of matrix:
10 14 18 22
15 22 29 36

Explanation of the Program

  • Matrix multiplication calculates the "dot product" of the rows of the first matrix against the columns of the second matrix.
  • Rule of Matrix Multiplication: The number of columns in the first matrix MUST equal the number of rows in the second matrix. This requires a third nested loop (k) to calculate the sliding dot product.

Complexity

Time Complexity O(r1 * c2 * r2) - Cubic time complexity.
Space Complexity O(r1 * c2) - To store the resulting matrix.
ADVERTISEMENT