Google News
logo
C++ Program to Multiply two Matrices by Passing Matrix to Function
In the following example of  C++ to multiply two matrices by passing matrices to a function :
Program :
#include <iostream>
using namespace std;

const int MAX = 100;

void multiplyMatrix(int mat1[][MAX], int mat2[][MAX], int res[][MAX], int r1, int c1, int r2, int c2)
{
    // Initializing elements of result matrix to 0
    for (int i = 0; i < r1; i++)
        for (int j = 0; j < c2; j++)
            res[i][j] = 0;
 
    // Multiplying matrices
    for (int i = 0; i < r1; i++)
        for (int j = 0; j < c2; j++)
            for (int k = 0; k < c1; k++)
                res[i][j] += mat1[i][k] * mat2[k][j];
}

int main()
{
    int r1, c1, r2, c2, mat1[MAX][MAX], mat2[MAX][MAX], res[MAX][MAX];

    // Taking input for the first matrix
    cout << "Enter number of rows and columns for first matrix: ";
    cin >> r1 >> c1;

    cout << "Enter elements of first matrix:\n";
    for (int i = 0; i < r1; i++)
        for (int j = 0; j < c1; j++)
            cin >> mat1[i][j];

    // Taking input for the second matrix
    cout << "Enter number of rows and columns for second matrix: ";
    cin >> r2 >> c2;

    cout << "Enter elements of second matrix:\n";
    for (int i = 0; i < r2; i++)
        for (int j = 0; j < c2; j++)
            cin >> mat2[i][j];

    // Checking if multiplication is possible
    if (c1 != r2)
    {
        cout << "Multiplication is not possible!\n";
        return 0;
    }

    // Calling the function to multiply matrices
    multiplyMatrix(mat1, mat2, res, r1, c1, r2, c2);

    // Printing the result
    cout << "Resultant matrix after multiplication is:\n";
    for (int i = 0; i < r1; i++)
    {
        for (int j = 0; j < c2; j++)
            cout << res[i][j] << " ";
        cout << endl;
    }

    return 0;
}
Output :
Enter number of rows and columns for first matrix: 2 3
Enter elements of first matrix:
5 7 3
2 0 8
Enter number of rows and columns for second matrix: 3 3
Enter elements of second matrix:
5 8 0
4 2 1
7 9 3
Resultant matrix after multiplication is:
74 81 16 
66 88 24 
Here, the function multiplyMatrix() takes four arguments - mat1, mat2, res, r1, c1, r2, and c2, where mat1 and mat2 are the two matrices to be multiplied, res is the resultant matrix, and r1, c1, r2, and c2 are the number of rows and columns of mat1 and mat2 respectively.

The function initializes the elements of the res matrix to 0, multiplies the matrices, and stores the result in the res matrix. The result is then printed in the main function.