Add Two Matrix

Add Two Matrix” is a basic operation which can be applied over two or more matrices. Here, we have given two matrices of dimension N*M and our task is to add the following matrices and store the result in resultant matrix.

CONDITION: The dimensions of the matrices to be added must be same. Otherwise, we cannot add two matrices.

Example:

Number of rows = 3

Number of columns = 3

111
222
333
Matrix 1

444
555
666
Matrix 2

555
777
999
Resultant Matrix

C++ Program to add two matrix is as follows:


/* Program to add two matrix */
#include<bits/stdc++.h>  
using namespace std;  
int main()  
 {  
    int N,M;  
    // Scan Dimensions of the matrix
    cout<<"Enter Row Size and Column Size of Matrix:\n";
    cin>>N>>M;  
      
    int matrix1[N][M];  
    int matrix2[N][M];  
    int result[N][M];  
      
    // Scan Matrix1 Elements  
    cout<<"Enter the Elements of First Matrix:\n";
    for(int i = 0 ; i < N ; i++)  
    for(int j = 0 ; j < M ; j++)  
    cin>>matrix1[i][j];  
      
    // Scan Matrix2 Elements  
    cout<<"Enter the Elements of Second Matrix:\n";
    for(int i = 0 ; i < N ; i++)  
    for(int j = 0 ; j < M ; j++)  
    cin>>matrix2[i][j];  
      
    // Adding matrices
    for(int i = 0 ; i < N ; i++)  
    for(int j = 0 ; j < M ; j++)  
    result[i][j] = matrix1[i][j]+matrix2[i][j];  
      
    //Print Resultant matrix 
    cout<<"The Resultant matrix is:\n";
    for(int i = 0 ; i < N ; i++)  
    {  
        for(int j = 0 ; j < M ; j++)  
        {  
            cout<<result[i][j]<<" ";  
        }  
        cout<<endl;  
    }  
}  

OUTPUT:
Enter Row Size and Column Size of Matrix:
3 3
Enter the Elements of First Matrix:
1 2 3
1 2 3
1 2 3
Enter the Elements of Second Matrix:
1 2 3
1 2 3
1 2 3
The Resultant matrix is:
2 4 6 
2 4 6 
2 4 6

Related Posts:

  1. Program to Transpose a Matrix.
  2. Program to Multiply Two Matrix.
  3. Program to check Identity Matrix.
  4. Program to check Idempotent Matrix.
  5. Program to check Involuntary Matrix.
  6. Program to print matrix in zig-zag order.
  7. Program to print matrix in spiral order.
  8. Program to sort a matrix.
  9. Program to Check whether given String is Palindrome or not.
  10. Program to convert lower-case alphabet to upper-case alphabet and vice-versa.
  11. Program to count total number of words in a string.
  12. Program to find smallest and largest word of the String.
  13. Program to find most frequent element in an array.
  14. Program to find pair in an array with given sum.
  15. Program to find first repeating element of an array.
  16. Program to merge two sorted arrays.
  17. Program to find missing number in an array.
  18. Program to sort if array is sorted.
  19. Program to print Alternate Elements of an Array.
  20. Program to swap kth element from beginning to kth element from end in an Array.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *