C++ Online Compiler
Example: Matrix Multiplication in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Matrix Multiplication #include <iostream> #include <vector> // Required for std::vector int main() { // Step 1: Define matrix dimensions const int R1 = 2; // Rows of Matrix A const int C1 = 3; // Columns of Matrix A (also Rows of Matrix B) const int R2 = 3; // Rows of Matrix B const int C2 = 2; // Columns of Matrix B // Check if multiplication is possible if (C1 != R2) { std::cout << "Error: Number of columns in Matrix A must be equal to number of rows in Matrix B." << std::endl; return 1; // Indicate an error } // Step 2: Initialize matrices A and B std::vector<std::vector<int>> matrixA = { {1, 2, 3}, {4, 5, 6} }; std::vector<std::vector<int>> matrixB = { {7, 8}, {9, 1}, {2, 3} }; // Step 3: Initialize result matrix C with zeros // C will have dimensions R1 x C2 std::vector<std::vector<int>> resultMatrixC(R1, std::vector<int>(C2, 0)); // Step 4: Perform matrix multiplication // Outer loop for rows of resultMatrixC (corresponds to rows of matrixA) for (int i = 0; i < R1; ++i) { // Middle loop for columns of resultMatrixC (corresponds to columns of matrixB) for (int j = 0; j < C2; ++j) { // Inner loop for sum of products (corresponds to columns of matrixA / rows of matrixB) for (int k = 0; k < C1; ++k) { resultMatrixC[i][j] += matrixA[i][k] * matrixB[k][j]; } } } // Step 5: Print the result matrix C std::cout << "Resultant Matrix C (" << R1 << "x" << C2 << "):" << std::endl; for (int i = 0; i < R1; ++i) { for (int j = 0; j < C2; ++j) { std::cout << resultMatrixC[i][j] << " "; } std::cout << std::endl; } return 0; }
Output
Clear
ADVERTISEMENTS