C++ Online Compiler
Example: Matrix Multiplication in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Matrix Multiplication #include <iostream> using namespace std; // Helper function to print a matrix void printMatrix(int matrix[][3], 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() { // For simplicity, we use fixed-size 3x3 matrices in this example. // In real applications, consider dynamic allocation or std::vector<std::vector<int>> // for matrices of arbitrary sizes. // Define two matrices for multiplication int matrixA[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int matrixB[3][3] = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} }; // Define the result matrix, initialized to zeros int resultMatrix[3][3] = {0}; int rowsA = 3, colsA = 3; int rowsB = 3, colsB = 3; // Step 1: Check if multiplication is possible // The number of columns in the first matrix must equal the number of rows in the second. if (colsA != rowsB) { cout << "Error: The number of columns in Matrix A (" << colsA << ") must be equal to the number of rows in Matrix B (" << rowsB << ")." << endl; cout << "Matrix multiplication is not possible." << endl; return 1; // Indicate an error } cout << "Matrix A:" << endl; printMatrix(matrixA, rowsA, colsA); cout << endl; cout << "Matrix B:" << endl; printMatrix(matrixB, rowsB, colsB); cout << endl; // Step 2: Perform matrix multiplication // The resulting matrix will have dimensions rowsA x colsB for (int i = 0; i < rowsA; ++i) { // Iterate over rows of the resultMatrix (and matrixA) for (int j = 0; j < colsB; ++j) { // Iterate over columns of the resultMatrix (and matrixB) for (int k = 0; k < colsA; ++k) { // Iterate over columns of matrixA (and rows of matrixB) resultMatrix[i][j] += matrixA[i][k] * matrixB[k][j]; } } } // Step 3: Display the result matrix cout << "Resultant Matrix (A * B):" << endl; printMatrix(resultMatrix, rowsA, colsB); // dimensions of result are rowsA x colsB return 0; }
Output
Clear
ADVERTISEMENTS