C++ Online Compiler
Example: Matrix Multiplication in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Matrix Multiplication #include <iostream> #include <vector> // Using vector for dynamic arrays, better practice than raw arrays // Function to print a matrix void printMatrix(const std::vector<std::vector<int>>& matrix) { for (const auto& row : matrix) { for (int val : row) { std::cout << val << "\t"; } std::cout << std::endl; } } int main() { // Define matrices A and B std::vector<std::vector<int>> matrixA = { {1, 2, 3}, {4, 5, 6} }; // 2x3 matrix std::vector<std::vector<int>> matrixB = { {7, 8}, {9, 1}, {2, 3} }; // 3x2 matrix // Get dimensions of matrices int rowA = matrixA.size(); int colA = matrixA[0].size(); int rowB = matrixB.size(); int colB = matrixB[0].size(); // Step 1: Check if multiplication is possible if (colA != rowB) { std::cout << "Error: Number of columns in Matrix A must be equal to number of rows in Matrix B." << std::endl; return 1; // Indicate error } // Step 2: Initialize result matrix C with appropriate dimensions (rowA x colB) std::vector<std::vector<int>> matrixC(rowA, std::vector<int>(colB, 0)); // Step 3: Perform matrix multiplication // Outer loop iterates through rows of matrixA (i) for (int i = 0; i < rowA; ++i) { // Middle loop iterates through columns of matrixB (j) for (int j = 0; j < colB; ++j) { // Inner loop calculates the dot product of row i of matrixA and column j of matrixB for (int k = 0; k < colA; ++k) { // colA can also be rowB, since they are equal matrixC[i][j] += matrixA[i][k] * matrixB[k][j]; } } } // Step 4: Print the matrices and their product std::cout << "Matrix A (" << rowA << "x" << colA << "):" << std::endl; printMatrix(matrixA); std::cout << "\nMatrix B (" << rowB << "x" << colB << "):" << std::endl; printMatrix(matrixB); std::cout << "\nResultant Matrix C (" << rowA << "x" << colB << "):" << std::endl; printMatrix(matrixC); return 0; }
Output
Clear
ADVERTISEMENTS