Tutorialspoint
Problem
Solution
Submissions

Multiply Two Matrices

Certification: Basic Level Accuracy: 66.67% Submissions: 6 Points: 15

Write a C++ program to multiply two matrices. The program should take two matrices as input and return their product. Ensure that the matrices are compatible for multiplication (i.e., the number of columns in the first matrix is equal to the number of rows in the second matrix).

Example 1
  • Input: Matrix A = [
     [1, 2],
     [3, 4] ]
     Matrix B = [
     [5, 6],
     [7, 8] ]
  • Output: [
     [19, 22],
     [43, 50] ]
  • Explanation:
    • Step 1: Verify that matrices are compatible for multiplication (A's columns = B's rows).
    • Step 2: Create a result matrix with dimensions (A's rows × B's columns).
    • Step 3: For each element in the result matrix, compute the dot product of the corresponding row in A and column in B.
    • Step 4: Return the result matrix.
Example 2
  • Input: Matrix A = [
     [1, 2, 3],
     [4, 5, 6] ]
     Matrix B = [
     [7, 8],
     [9, 10],
     [11, 12] ]
  • Output: [
     [58, 64],
     [139, 154] ]
  • Explanation:
    • Step 1: Verify that matrices are compatible for multiplication (A's columns = B's rows, 3 = 3).
    • Step 2: Create a result matrix with dimensions (A's rows × B's columns) = (2 × 2).
    • Step 3: For each element in the result matrix, compute the dot product of the corresponding row in A and column in B.
    • Step 4: Return the result matrix.
Constraints
  • The number of columns in the first matrix must be equal to the number of rows in the second matrix
  • The matrices can have a maximum size of 100×100
  • Time Complexity: O(n^3), where n is the size of the matrices
  • Space Complexity: O(n^2)
ArraysControl StructuresIBMDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use nested loops to iterate through the rows of the first matrix and the columns of the second matrix.
  • Use a temporary variable to store the sum of the products of corresponding elements.
  • Ensure that the matrices are compatible for multiplication before performing the operation.

Steps to solve by this approach:

 Step 1: Define a function multiply_matrices that takes two 2D arrays and a result array as parameters.
 Step 2: Use three nested loops to perform matrix multiplication.
 Step 3: Initialize each result element to zero before accumulating products.
 Step 4: Apply the formula: result[i][j] += A[i][k] * B[k][j] for each element.
 Step 5: In main, read dimensions and values for both matrices from input.
 Step 6: Check if matrices can be multiplied based on their dimensions.
 Step 7: Call the function and output the resulting matrix.

Submitted Code :