Home » Interview » Matrix Interview Questions » Multiplication of two matrices

Multiplication of two matrices


Given two matrices, this function will multiply the two matrices and prints the result. Here, necessary and sufficient condition is the number of columns in A should be equal to the number of rows in matrix B.

Example

INPUT

A[4][4] = { {1, 1, 1, 1},
{1, 6, 7, 6},
{6, 3, 7, 12},
{4, 4, 4, 4}};

B[4][4] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 9, 1, 7}};

OUTPUT
10  15  7  13
58  88  40  76
81  141  45  117
40  60  28  52

In the above example, we got the first element in output by multiplying all the respective elements in first row of matrix A with the elements in the first column of matrix B and adding them. Similarly for the second element in first row of the output, we need to take first row of matrix A and second column of matrix B. In this way we got all the elements in output matrix

Time Complexity: O(n^3),

here n is the size of the matrix

Algorithm

1. Simply run three loops
2. Loop for each row in matrix A with variable i
3. Inside the above loop, Loop for each column in matrix B with variable j
4. Inside the above two loops, Loop for each row element in matrix A with variable k and each column element in matrix B with variable k  ie, A[i][k] and B[k][j] .
5. we will find the product of each row element in A with each colum element in B. ie, A[i][k] * B[k][j] and add all the products and store in new matrix C ie, C[i][j]
6. matrix C is the multiplication output

C++ Program

#include <bits/stdc++.h>
using namespace std;
#define N 4
int main()
{
	int A[N][N] = { {1, 1, 1, 1},
					{1, 6, 7, 6},
					{6, 3, 7, 12},
					{4, 4, 4, 4}};

	int B[N][N] = { {1, 1, 1, 1},
                    {2, 2, 2, 2},
                    {3, 3, 3, 3},
                    {4, 9, 1, 7}};
	
	int C[N][N];
	for(int i=0; i <N; i++)
	{
		for(int j=0; j<N; j++)
			{int sum = 0;
				for(int k=0;k<N;k++)
				{
					sum += A[i][k] * B[k][j];
				}
			C[i][j] = sum;
			cout <<C[i][j] <<"  ";
			}
		cout<<endl;
	}
	

	return 0;
}

Try It