Monday, November 18, 2024
Google search engine
HomeData Modelling & AIC++ Program For Addition of Two Matrices

C++ Program For Addition of Two Matrices

Given two N x M matrices. Find a N x matrix as the sum of given matrices each value at the sum of values of corresponding elements of the given two matrices. In this article, we will learn about the addition of two matrices.

Addition of Two Matrices

 

Approach

Below is the idea to solve the problem.

  1. Iterate over every cell of the matrix (i, j).
  2. Add the corresponding values of the two matrices.
  3. Store in a single matrix i.e. the resultant matrix.

Algorithm

  1. Initialize a resultant matrix res[N][M].
  2. Run a for loop for counter i as each row and in each iteration:
    1. Run a for loop for counter j as each column and in each iteration:
      1. Add values of the two matrices for index i, j, and store in res[i][j].
  3. Return res.

Below is the Implementation of the above approach:

C++




// C++ program for addition
// of two matrices
#include <bits/stdc++.h>
using namespace std;
#define N 4
 
// This function adds A[][] and B[][],
// and stores the result in C[][]
void add(int A[][N], int B[][N], int C[][N])
{
    int i, j;
    for (i = 0; i < N; i++)
        for (j = 0; j < N; j++)
            C[i][j] = A[i][j] + B[i][j];
}
 
// Driver code
int main()
{
    int A[N][N] = { { 1, 1, 1, 1 },
                    { 2, 2, 2, 2 },
                    { 3, 3, 3, 3 },
                    { 4, 4, 4, 4 } };
 
    int B[N][N] = { { 1, 1, 1, 1 },
                    { 2, 2, 2, 2 },
                    { 3, 3, 3, 3 },
                    { 4, 4, 4, 4 } };
 
    // To store the result
    int C[N][N];
    int i, j;
    add(A, B, C);
 
    cout << "Result matrix is " << endl;
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++)
            cout << C[i][j] << " ";
        cout << endl;
    }
 
    return 0;
}


Output

Result matrix is 
2 2 2 2 
4 4 4 4 
6 6 6 6 
8 8 8 8 

The complexity of the above method

Time Complexity: O(n2). 

Auxiliary Space: O(n2)

The program can be extended for rectangular matrices. The following post can be useful for extending this program: How to pass a 2D array as a parameter in C?

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments