C++ Online Compiler
Example: Matrix Multiplication Using Functions in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Matrix Multiplication Using Functions #include <iostream> #include <vector> // Required for std::vector using namespace std; // Function to get matrix input from the user void inputMatrix(vector<vector<int>>& matrix, int rows, int cols) { cout << "Enter elements for the matrix (" << rows << "x" << cols << "):" << endl; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { cout << "Enter element at [" << i << "][" << j << "]: "; cin >> matrix[i][j]; } } } // Function to multiply two matrices vector<vector<int>> multiplyMatrices(const vector<vector<int>>& matrixA, const vector<vector<int>>& matrixB, int r1, int c1, int r2, int c2) { // Check if multiplication is possible if (c1 != r2) { cout << "Error: Number of columns in the first matrix must be equal to the number of rows in the second matrix." << endl; // Return an empty matrix to indicate error or handle differently return {}; } // Initialize result matrix with dimensions r1 x c2, filled with zeros vector<vector<int>> resultMatrix(r1, vector<int>(c2, 0)); // Perform matrix multiplication for (int i = 0; i < r1; ++i) { // Iterate over rows of matrix A for (int j = 0; j < c2; ++j) { // Iterate over columns of matrix B for (int k = 0; k < c1; ++k) { // Iterate over columns of A OR rows of B resultMatrix[i][j] += matrixA[i][k] * matrixB[k][j]; } } } return resultMatrix; } // Function to display a matrix void displayMatrix(const vector<vector<int>>& matrix) { if (matrix.empty() || matrix[0].empty()) { cout << "Matrix is empty or invalid." << endl; return; } cout << "Resultant Matrix:" << endl; for (const auto& row : matrix) { for (int val : row) { cout << val << "\t"; } cout << endl; } } int main() { // Step 1: Declare dimensions for the two matrices int r1, c1, r2, c2; cout << "Enter dimensions for Matrix A (rows cols): "; cin >> r1 >> c1; cout << "Enter dimensions for Matrix B (rows cols): "; cin >> r2 >> c2; // Step 2: Create matrices using std::vector<std::vector<int>> vector<vector<int>> matrixA(r1, vector<int>(c1)); vector<vector<int>> matrixB(r2, vector<int>(c2)); // Step 3: Get input for Matrix A inputMatrix(matrixA, r1, c1); // Step 4: Get input for Matrix B inputMatrix(matrixB, r2, c2); // Step 5: Perform matrix multiplication using the function vector<vector<int>> resultMatrix = multiplyMatrices(matrixA, matrixB, r1, c1, r2, c2); // Step 6: Display the result matrix if (!resultMatrix.empty()) { // Check if multiplication was successful (not an empty error matrix) displayMatrix(resultMatrix); } else { cout << "Matrix multiplication could not be performed due to incompatible dimensions." << endl; } return 0; }
Output
Clear
ADVERTISEMENTS