
Problem
Solution
Submissions
Sum of Two Matrices
Certification: Basic Level
Accuracy: 100%
Submissions: 4
Points: 10
Write a C++ program to find the sum of two matrices. The program should take two matrices of the same size as input and return their sum.
Example 1
- Input:
Matrix A = [
[1, 2],
[3, 4]
] Matrix B = [
[5, 6],
[7, 8]
] - Output: [
[6, 8],
[10, 12]
] - Explanation:
- Step 1: Verify that matrices A and B have the same dimensions (2×2).
- Step 2: Create a result matrix with the same dimensions.
- Step 3: Add corresponding elements: result[0][0] = A[0][0] + B[0][0] = 1 + 5 = 6.
- Step 4: Continue for all elements: result[0][1] = 2 + 6 = 8, result[1][0] = 3 + 7 = 10, result[1][1] = 4 + 8 = 12.
- Step 5: Return the resulting matrix.
Example 2
- Input:
Matrix A = [
[1, 2, 3],
[4, 5, 6]
] Matrix B = [
[7, 8, 9],
[10, 11, 12]
] - Output: [
[8, 10, 12],
[14, 16, 18]
] - Explanation:
- Step 1: Verify that matrices A and B have the same dimensions (2×3).
- Step 2: Create a result matrix with the same dimensions.
- Step 3: Add corresponding elements for each position in the matrices.
- Step 4: For the first row: [1+7, 2+8, 3+9] = [8, 10, 12].
- Step 5: For the second row: [4+10, 5+11, 6+12] = [14, 16, 18].
- Step 6: Return the resulting matrix.
Constraints
- The matrices must be of the same size
- The matrices can have a maximum size of 100×100
- Time Complexity: O(n²), where n is the size of the matrices
- Space Complexity: O(n²) for storing the result matrix
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 matrices and add corresponding elements.
- Store the result in a new matrix.