Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Add Two Matrix Using Multi-Dimensional Arrays in C++



A matrix is a rectangular array of numbers arranged in rows and columns. To add two matrices, they must be the same size. We add each number in the first matrix to the number in the same position in the second matrix to get a new matrix

An example of the addition of two matrices is as follow:

addition of matrices

Adding Two Matrices Using Multidimensional Arrays

To add two matrices in C++, we use multidimensional arrays. These arrays help us store matrix values in rows and columns, just like a real matrix. Then, we add the two matrices stored in these arrays. Below are the steps we took.

  • We first define the number of rows and columns for the matrices.
  • Next, we create two 2D arrays, a and b, and initialize them with values to represent the two matrices.
  • Then, we add each element from the first matrix to the element in the same position in the second matrix. The result is stored in another 2D array called sum.
  • Finally, we print the sum matrix, which shows the result of the addition.

C++ Program to Add Two Matrices Using Multi-dimensional Arrays

Here's a complete C++ program where we add two matrices using multi-dimensional arrays.

#include <iostream>
using namespace std;

int main() {
   int r = 2, c = 4, sum[2][4], i, j;

   // Define the first matrix
   int a[2][4] = { {1, 5, 9, 4}, {3, 2, 8, 3} };
   
   // Define the second matrix
   int b[2][4] = { {6, 3, 8, 2}, {1, 5, 2, 9} };
   
   // Print the first matrix
   cout << "The first matrix is: " << endl;
   for(i = 0; i < r; ++i) {
      for(j = 0; j < c; ++j)
         cout << a[i][j] << " ";
      cout << endl;
   }

   cout << endl;

   // Print the second matrix
   cout << "The second matrix is: " << endl;
   for(i = 0; i < r; ++i) {
      for(j = 0; j < c; ++j)
         cout << b[i][j] << " ";
      cout << endl;
   }

   cout << endl;

   // Add the two matrices and store the result in sum
   for(i = 0; i < r; ++i)
      for(j = 0; j < c; ++j)
         sum[i][j] = a[i][j] + b[i][j];

   // Print the result matrix
   cout << "Sum of the two matrices is:" << endl;
   for(i = 0; i < r; ++i) {
      for(j = 0; j < c; ++j)
         cout << sum[i][j] << " ";
      cout << endl;
   }
   return 0;
}

Below you will see the output of the above program which shows the addition of two matrices, you can even modify the matrices to check different matrices.

The first matrix is: 
1 5 9 4 
3 2 8 3 

The second matrix is: 
6 3 8 2 
1 5 2 9 

Sum of the two matrices is:
7 8 17 6 
4 7 10 12 

Time Complexity: O(r*c) because the program processes each element of the matrices once.

Space Complexity: O(r*c)the program uses memory to store three matrices, each having r rows and c columns.

Updated on: 2025-05-15T19:42:23+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements