# C# program to multiply two matrices

CsharpProgrammingServer Side Programming

The program for matrix multiplication is used to multiply two matrices. This procedure is only possible if the number of columns in the first matrix are equal to the number of rows in the second matrix.

A program that demonstrates matrix multiplication in C# is given as follows −

## Example

Live Demo

using System;
namespace MatrixMultiplicationDemo {
class Example {
static void Main(string[] args) {
int m = 2, n = 3, p = 3, q = 3, i, j;
int[,] a = {{1, 4, 2}, {2, 5, 1}};
int[,] b = {{3, 4, 2}, {3, 5, 7}, {1, 2, 1}};
Console.WriteLine("Matrix a:");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
Console.Write(a[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine("Matrix b:");
for (i = 0; i < p; i++) {
for (j = 0; j < q; j++) {
Console.Write(b[i, j] + " ");
}
Console.WriteLine();
}
if(n! = p) {
Console.WriteLine("Matrix multiplication not possible");
} else {
int[,] c = new int[m, q];
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
c[i, j] = 0;
for (int k = 0; k < n; k++) {
c[i, j] += a[i, k] * b[k, j];
}
}
}
Console.WriteLine("The product of the two matrices is :");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
Console.Write(c[i, j] + "\t");
}
Console.WriteLine();
}
}
}
}
}

## Output

The output of the above program is given as follows.

Matrix a:
1 4 2
2 5 1
Matrix b:
3 4 2
3 5 7
1 2 1
The product of the two matrices is :
172832
223540

Now let us understand the above program.

First, the two matrices a and b are displayed. The code snippet for this is given as follows.

for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
Console.Write(a[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine("Matrix b:");
for (i = 0; i < p; i++) {
for (j = 0; j < q; j++) {
Console.Write(b[i, j] + " ");
}
Console.WriteLine();
}

If the number of columns in the first matrix are not equal to the number of rows in the second matrix then the matrices cannot be multiplied and this is displayed. The code snippet for this is given as follows .

if(n! = p) {
Console.WriteLine("Matrix multiplication not possible");
}

Otherwise, a nested for loop is used to obtain the product of matrices a and b i.e. matrix c. Then the matrix c is displayed. The code snippet for this is given as follows −

for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
c[i, j] = 0;
for (int k = 0; k < n; k++) {
c[i, j] += a[i, k] * b[k, j];
}
}
}
Console.WriteLine("The product of the two matrices is :");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
Console.Write(c[i, j] + "\t");
}
Console.WriteLine();
}
Published on 23-Nov-2018 06:28:46