C++ Code for Addition of Two Matrices:
```cpp
#include <iostream>
using namespace std;
const int MAX = 100; // Maximum size for matrices (adjust as needed)
Function to add two matrices
void addMatrices(int mat1[][MAX], int mat2[][MAX], int result[][MAX], int rows, int cols) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
}
Function to display a matrix
void displayMatrix(int matrix[][MAX], int rows, int cols) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
int main() {
int rows, cols;
cout << "Enter the number of rows and columns for matrices: ";
cin >> rows >> cols;
int matrix1[MAX][MAX], matrix2[MAX][MAX], result[MAX][MAX];
cout << "Enter elements of matrix 1:" << endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> matrix1[i][j];
}
}
cout << "Enter elements of matrix 2:" << endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> matrix2[i][j];
}
}
Call function to add matrices
addMatrices(matrix1, matrix2, result, rows, cols);
Displaying the resulting matrix
cout << "Resultant matrix after addition:" << endl;
displayMatrix(result, rows, cols);
return 0;
}
```
Explanation:
- The program asks the user to input the number of rows and columns for the matrices.
- Then, it takes input for the elements of two matrices: `matrix1` and `matrix2`.
- The `addMatrices` function iterates through the matrices and adds corresponding elements, storing the result in the `result` matrix.
- Finally, the program displays the resulting matrix using the `displayMatrix` function.
This program allows the user to input the matrices and performs addition based on the entered values, demonstrating how to add two matrices in C++.
Example:
Suppose we have two 2x2 matrices:
```
Matrix 1:
1 2
3 4
Matrix 2:
5 6
7 8
```
After adding these matrices, the resultant matrix would be:
```
Resultant Matrix:
6 8
10 12
```
0 Comments