
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)
Editorial
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. |
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.