C++ Online Compiler
Example: Naive Matrix Multiplication in C
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Naive Matrix Multiplication #include <iostream> #include <vector> // Helper function to print a matrix void printMatrix(const std::vector<std::vector<int>>& matrix) { // Step 1: Iterate through each row of the matrix. for (const auto& row : matrix) { // Step 2: Iterate through each element in the current row. for (int val : row) { // Step 3: Print the element followed by a space. std::cout << val << " "; } // Step 4: Move to the next line after printing all elements in a row. std::cout << std::endl; } } // Function to perform naive matrix multiplication std::vector<std::vector<int>> multiplyNaive(const std::vector<std::vector<int>>& A, const std::vector<std::vector<int>>& B) { int n = A.size(); // Assuming square matrices of size n x n // Step 1: Initialize the result matrix C with dimensions n x n, filled with zeros. std::vector<std::vector<int>> C(n, std::vector<int>(n, 0)); // Step 2: Iterate through rows of matrix A. for (int i = 0; i < n; ++i) { // Step 3: Iterate through columns of matrix B. for (int j = 0; j < n; ++j) { // Step 4: Iterate through elements for the sum of products. for (int k = 0; k < n; ++k) { // Step 5: Accumulate the product A[i][k] * B[k][j] into C[i][j]. C[i][j] += A[i][k] * B[k][j]; } } } // Step 6: Return the resulting product matrix C. return C; } int main() { // Step 1: Define matrices A and B (2x2 example). std::vector<std::vector<int>> A = {{1, 2}, {3, 4}}; std::vector<std::vector<int>> B = {{5, 6}, {7, 8}}; int n = A.size(); if (n == 0 || A[0].size() != n || B.size() != n || B[0].size() != n) { std::cout << "Invalid matrix dimensions for square matrices." << std::endl; return 1; } // Step 2: Print original matrices for clarity. std::cout << "Matrix A:" << std::endl; printMatrix(A); std::cout << "\nMatrix B:" << std::endl; printMatrix(B); // Step 3: Perform naive matrix multiplication. std::vector<std::vector<int>> C = multiplyNaive(A, B); // Step 4: Print the result matrix. std::cout << "\nResult of Naive Multiplication (C = A * B):" << std::endl; printMatrix(C); return 0; }
Output
Clear
ADVERTISEMENTS