Tutorialspoint
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
ArraysControl StructuresDeloitteSwiggy
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 matrices and add corresponding elements.
  • Store the result in a new matrix.

Steps to solve by this approach:

 Step 1: Define a function sum_matrices that takes two constant 2D vectors as parameters.
 Step 2: Extract the number of rows and columns from the first matrix.
 Step 3: Create a result matrix with the same dimensions, initialized with zeros.
 Step 4: Use nested loops to iterate through each element of both matrices.
 Step 5: Add corresponding elements and store in the result matrix.
 Step 6: Return the resulting matrix.
 Step 7: In main, create two matrices, call the function, and print the result.

Submitted Code :