WAP to add two matrix
Objective
Write a C++ program to add two 2D Matrices.
Algorithm / Approach
- Declare three 3x3 matrices:
m1,m2, andm3. - Use nested loops (rows
i, columnsj) to read data intom1andm2. - Use nested loops to add the matrices mathematically:
m3[i][j] = m1[i][j] + m2[i][j]. - Print the resulting
m3matrix.
main.cpp
#include<iostream>
using namespace std;
int main() {
int m1[3][3],m2[3][3],m3[3][3];
cout<<"Enter Elements of Mat1: \n";
for(int i = 0; i< 3; i++) {
for(int j = 0; j< 3; j++) {
cin>>m1[i][j];
}
}
cout<<"Enter Elements of Mat2: \n";
for(int i = 0; i< 3; i++) {
for(int j = 0; j< 3; j++) {
cin>>m2[i][j];
}
}
cout<<"Sum of the matrix: \n";
for(int i = 0; i< 3; i++) {
for(int j = 0; j< 3; j++) {
m3[i][j] = m1[i][j]+m2[i][j];
cout<< m3[i][j]<<" ";
}
cout<< endl;
}
return 0;
}
Expected Output
Enter Elements of Mat1: 1 2 3 2 3 4 6 8 2 Enter Elements of Mat2: 3 4 2 1 2 1 3 1 2 Sum of the matrix: 4 6 5 3 5 5 9 9 4
Explanation of the Program
- A 2D array (matrix) is essentially an array of arrays. The first index represents the row, and the second represents the column.
- Matrix addition is straightforward: you simply add the elements that share the exact same coordinates (e.g., Row 0 Col 0 of M1 + Row 0 Col 0 of M2).
Complexity
Time Complexity
O(r * c) - Where r is rows and c is columns.
Space Complexity
O(r * c) - For storing the 3 matrices.