C++ Code for Multiplication of Two Matrices:
```cpp
#include <iostream>
using namespace std;
const int MAX = 100; // Maximum size for matrices (adjust as needed)
Function to multiply two matrices
void multiplyMatrices(int mat1[][MAX], int mat2[][MAX], int result[][MAX], int rows1, int cols1, int rows2, int cols2) {
if (cols1 != rows2) {
cout << "Cannot multiply matrices. Columns of matrix 1 should be equal to rows of matrix 2.";
return;
}
for (int i = 0; i < rows1; ++i) {
for (int j = 0; j < cols2; ++j) {
result[i][j] = 0;
for (int k = 0; k < cols1; ++k) {
result[i][j] += mat1[i][k] * mat2[k][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 rows1, cols1, rows2, cols2;
cout << "Enter the number of rows and columns for matrix 1: ";
cin >> rows1 >> cols1;
cout << "Enter the number of rows and columns for matrix 2: ";
cin >> rows2 >> cols2;
if (cols1 != rows2) {
cout << "Cannot multiply matrices. Columns of matrix 1 should be equal to rows of matrix 2.";
return 0;
}
int matrix1[MAX][MAX], matrix2[MAX][MAX], result[MAX][MAX];
cout << "Enter elements of matrix 1:" << endl;
for (int i = 0; i < rows1; ++i) {
for (int j = 0; j < cols1; ++j) {
cin >> matrix1[i][j];
}
}
cout << "Enter elements of matrix 2:" << endl;
for (int i = 0; i < rows2; ++i) {
for (int j = 0; j < cols2; ++j) {
cin >> matrix2[i][j];
}
}
Call function to multiply matrices
multiplyMatrices(matrix1, matrix2, result, rows1, cols1, rows2, cols2);
Displaying the resulting matrix
cout << "Resultant matrix after multiplication:" << endl;
displayMatrix(result, rows1, cols2);
return 0;
}
Explanation:
- The program asks the user to input the number of rows and columns for both matrices.
- It checks if the matrices can be multiplied by comparing their dimensions.
- Then, it takes input for the elements of two matrices: `matrix1` and `matrix2`.
- The `multiplyMatrices` function multiplies the matrices using three nested loops to perform the matrix multiplication.
- Finally, the program displays the resulting matrix using the `displayMatrix` function.
This program allows the user to input matrices and performs matrix multiplication based on the entered values, demonstrating how to multiply two matrices in C++
Example:
Suppose we have two matrices:
```
Matrix 1:
1 2
3 4
Matrix 2:
5 6
7 8
```
After multiplying these matrices, the resultant matrix would be:
Resultant Matrix:
19 22
43 50
0 Comments