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);