141 views
Matrix Multiplication in C++
Matrix multiplication is a fundamental operation in linear algebra, and you can perform matrix multiplication in C++ using nested loops. Here’s a simple example of how to multiply two matrices:
C++
#include <iostream>
int main() {
int rowsA, colsA, rowsB, colsB;
// Input dimensions of the first matrix (A)
std::cout << "Enter the number of rows and columns of matrix A: ";
std::cin >> rowsA >> colsA;
// Input dimensions of the second matrix (B)
std::cout << "Enter the number of rows and columns of matrix B: ";
std::cin >> rowsB >> colsB;
if (colsA != rowsB) {
std::cout << "Matrix multiplication is not possible. The number of columns in A must be equal to the number of rows in B." << std::endl;
return 1; // Exit with an error code
}
// Initialize matrices A and B
int A[rowsA][colsA], B[rowsB][colsB];
// Input matrix A
std::cout << "Enter elements of matrix A:" << std::endl;
for (int i = 0; i < rowsA; ++i) {
for (int j = 0; j < colsA; ++j) {
std::cin >> A[i][j];
}
}
// Input matrix B
std::cout << "Enter elements of matrix B:" << std::endl;
for (int i = 0; i < rowsB; ++i) {
for (int j = 0; j < colsB; ++j) {
std::cin >> B[i][j];
}
}
// Initialize the result matrix (C) with zeros
int C[rowsA][colsB] = {0};
// Perform matrix multiplication
for (int i = 0; i < rowsA; ++i) {
for (int j = 0; j < colsB; ++j) {
for (int k = 0; k < colsA; ++k) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
// Display the result matrix (C)
std::cout << "Result matrix C:" << std::endl;
for (int i = 0; i < rowsA; ++i) {
for (int j = 0; j < colsB; ++j) {
std::cout << C[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
In this program:
- The user is prompted to enter the dimensions of two matrices, A and B.
- The program checks if the dimensions are valid for multiplication (i.e., the number of columns in A must be equal to the number of rows in B). If not, it prints an error message and exits.
- Matrices A and B are initialized and filled with user input.
- Matrix C, the result of multiplication, is initialized with zeros.
- Matrix multiplication is performed using nested loops. The result is stored in matrix C.
- The program displays the result matrix C.
Compile and run this program to perform matrix multiplication with your input matrices A and B.