Program to Multiply Two Matrices Using Multi-dimensional Arrays - (C# Basic Programs)
Multiplying two matrices is a common mathematical operation in programming, and it is frequently used in scientific applications. In this tutorial, we will discuss a C# program to multiply two matrices using multi-dimensional arrays.
Syntax
The syntax for multiplying two matrices using multi-dimensional arrays in C# is as follows:
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i, j] += matrix1[i, k] * matrix2[k, j];
}
}
}
Example
using System;
namespace MatrixMultiplication
{
class Program
{
static void Main(string[] args)
{
int rows1 = 2, cols1 = 3;
int rows2 = 3, cols2 = 2;
int[,] matrix1 = { { 1, 2, 3 },
{ 4, 5, 6 } };
int[,] matrix2 = { { 1, 2 },
{ 3, 4 },
{ 5, 6 } };
int[,] result = new int[rows1, cols2];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i, j] += matrix1[i, k] * matrix2[k, j];
}
}
}
Console.WriteLine("Result:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
Console.Write(result[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
Output:
Result:
22 28
49 64
Explanation
The program initializes two matrices, matrix1 and matrix2, and multiplies them using a nested loop structure. The outer loop iterates through the rows of the first matrix, the middle loop iterates through the columns of the second matrix, and the inner loop calculates the dot product of the corresponding row from the first matrix and column from the second matrix. The result of this dot product is then added to the corresponding cell in the result matrix.
Use
The program to multiply two matrices using multi-dimensional arrays is useful in many scientific and engineering applications. It can be used to solve systems of linear equations, to simulate electrical circuits, and to analyze data from experiments.
Summary
In this tutorial, we discussed a C# program to multiply two matrices using multi-dimensional arrays. We covered the syntax, an example, explanation, use and how this program can be useful in various scientific and engineering applications. By understanding this program, developers can expand their knowledge of the C# programming language and develop more complex applications.