Thursday, June 24, 2021
Home coding Write a program to add two matrix.

Write a program to add two matrix.

Given a two matrix we have to calculate the sum of two matrix and stored the result into a resultant matrix.

Addition of matrix is same like we add two integer.C=A+B.

Example:

input:
1 2
3 4

3 4
5 6
output:
4 6
8 10 

Logic

add the value of first matrix of same row column to second matrix of same row column.

#include<bits/stdc++.h>
using namespace std;
int main() {
    int matrix1[10][10],matrix2[10][10] ,addition[10][10];
    int row, col, i, j;
    cout<<"Enter rows and columns: "<<endl;
    cin>>row>>col;

    cout<<" Enter matrix1 elements:"<<endl;
    for (i = 0; i < row; ++i)
    {
        for (j = 0; j < col; ++j) 
        {
         cin>>matrix1[i][j];
        }
    }

 cout<<" Enter matrix2 elements:"<<endl;
  for (i = 0; i < row; ++i)
    {
        for (j = 0; j < col; ++j) 
        {
         cin>>matrix2[i][j];
        }
    }

   
    for (i = 0; i < row; ++i)
    {
        for (j = 0; j < col; ++j) {
         addition[i][j] = matrix1[i][j]+matrix2[i][j];
        }
}
   
    cout<<"Addition of the matrix:"<<endl;
    for (i = 0; i < col; ++i)
    {
        for (j = 0; j < row; ++j) {
            cout<<addition[i][j]<<" ";
            if (j == row-1)
            {
                cout<<endl;
            }
     }   }
    
}

Output:

Enter rows and columns: 2 2
 Enter matrix1 elements: 1 2 3 4
 Enter matrix2 elements:5 6 7 8
Addition of the matrix:
6 8 
10 12 

Time Complexity=O(N*N)

Space Complexity=O(N*N);

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments