The Program in C# Program for Multiplication of two square Matrices is given below:
using System;
namespace MatrixMultiplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Codeauri Family, enter the number of rows/columns in the matrices: ");
int n = int.Parse(Console.ReadLine());
int[,] firstMatrix = new int[n, n];
int[,] secondMatrix = new int[n, n];
int[,] resultMatrix = new int[n, n];
Console.WriteLine("Enter the elements of the first matrix: ");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
firstMatrix[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("Enter the elements of the second matrix: ");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
secondMatrix[i, j] = int.Parse(Console.ReadLine());
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
resultMatrix[i, j] += firstMatrix[i, k] * secondMatrix[k, j];
}
}
}
Console.WriteLine("Okay, the result matrix after multiplication is: ");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(resultMatrix[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
Output:
Hello Codeauri Family, enter the number of rows/columns in the matrices:
2
Enter the elements of the first matrix:
4
7
6
9
Enter the elements of the second matrix:
3
5
1
2
Okay, the result matrix after multiplication is:
19 34
27 48
Pro-Tips💡
Here are the steps by steps execution of above program:
- The first line
using System;
includes the System namespace, which contains various classes and methods. - The code defines a namespace
MatrixMultiplication
to group together related classes. - Within the
MatrixMultiplication
namespace, the code defines a classProgram
with aMain
method that is the entry point of the program. - The program prompts the user to enter the number of rows/columns in the matrices using
Console.WriteLine
method. - The program uses the entered value to declare two two-dimensional arrays
firstMatrix
andsecondMatrix
and another two-dimensional arrayresultMatrix
to store the result of the matrix multiplication. - The program then prompts the user to enter the elements of the first matrix and stores them in the
firstMatrix
array. - The program then prompts the user to enter the elements of the second matrix and stores them in the
secondMatrix
array. - The program then uses a nested for loop to multiply the matrices and store the result in the
resultMatrix
array. - The program finally displays the result matrix using another nested for loop.
- The program ends with the
Console.WriteLine
method, which writes a blank line to the console.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.