C++ Online Compiler
Example: 3x3 Matrix Multiplication in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// 3x3 Matrix Multiplication #include <iostream> #include <iomanip> // For std::setw int main() { // Step 1: Declare and initialize two 3x3 matrices (matrixA, matrixB) 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} }; // Step 2: Declare a 3x3 matrix to store the result (resultMatrix) int resultMatrix[3][3]; // Step 3: Initialize resultMatrix with zeros for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { resultMatrix[i][j] = 0; } } // Step 4: Perform matrix multiplication // Outer loops iterate through rows of matrixA (i) and columns of matrixB (j) for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { // Inner loop calculates the dot product of row 'i' of matrixA // and column 'j' of matrixB for (int k = 0; k < 3; ++k) { resultMatrix[i][j] += matrixA[i][k] * matrixB[k][j]; } } } // Step 5: Print the original matrices for verification std::cout << "Matrix A:" << std::endl; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { std::cout << std::setw(4) << matrixA[i][j]; } std::cout << std::endl; } std::cout << "\nMatrix B:" << std::endl; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { std::cout << std::setw(4) << matrixB[i][j]; } std::cout << std::endl; } // Step 6: Print the resulting matrix std::cout << "\nResultant Matrix (A * B):" << std::endl; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { std::cout << std::setw(4) << resultMatrix[i][j]; } std::cout << std::endl; } return 0; }
Output
Clear
ADVERTISEMENTS