C++ Online Compiler
Example: Matrix Multiplication in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Matrix Multiplication #include <iostream> // For input/output operations #include <vector> // For using std::vector to represent matrices // Function to get matrix dimensions and elements from the user void getMatrixInput(int& rows, int& cols, std::vector<std::vector<int>>& matrix) { std::cout << "Enter number of rows: "; std::cin >> rows; std::cout << "Enter number of columns: "; std::cin >> cols; matrix.resize(rows, std::vector<int>(cols)); // Resize matrix to given dimensions std::cout << "Enter matrix elements (" << rows << "x" << cols << "):\n"; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { std::cout << "Enter element [" << i << "][" << j << "]: "; std::cin >> matrix[i][j]; } } } // Function to display a matrix void displayMatrix(const std::vector<std::vector<int>>& matrix) { for (const auto& row : matrix) { for (int element : row) { std::cout << element << "\t"; } std::cout << "\n"; } } int main() { // Step 1: Declare variables for matrix dimensions and the matrices themselves int rows1, cols1, rows2, cols2; std::vector<std::vector<int>> matrix1; std::vector<std::vector<int>> matrix2; std::vector<std::vector<int>> resultMatrix; // Step 2: Get input for the first matrix std::cout << "--- Enter details for Matrix 1 ---\n"; getMatrixInput(rows1, cols1, matrix1); // Step 3: Get input for the second matrix std::cout << "\n--- Enter details for Matrix 2 ---\n"; getMatrixInput(rows2, cols2, matrix2); // Step 4: Check for matrix compatibility // For multiplication, columns of matrix1 must equal rows of matrix2 if (cols1 != rows2) { std::cout << "\nError: Matrices are not compatible for multiplication.\n"; std::cout << "Number of columns in Matrix 1 (" << cols1 << ") must be equal to number of rows in Matrix 2 (" << rows2 << ").\n"; return 1; // Indicate an error } // Step 5: Initialize the result matrix dimensions // The result matrix will have rows1 rows and cols2 columns resultMatrix.resize(rows1, std::vector<int>(cols2, 0)); // Initialize all elements to 0 // Step 6: Perform matrix multiplication // The core logic for matrix multiplication uses three nested loops for (int i = 0; i < rows1; ++i) { // Iterate through rows of matrix1 for (int j = 0; j < cols2; ++j) { // Iterate through columns of matrix2 for (int k = 0; k < cols1; ++k) { // Iterate through columns of matrix1 (or rows of matrix2) resultMatrix[i][j] += matrix1[i][k] * matrix2[k][j]; } } } // Step 7: Display the input matrices std::cout << "\n--- Matrix 1 ---\n"; displayMatrix(matrix1); std::cout << "\n--- Matrix 2 ---\n"; displayMatrix(matrix2); // Step 8: Display the result matrix std::cout << "\n--- Product Matrix ---\n"; displayMatrix(resultMatrix); return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS