Matrix Multiplication in C# 5


The Perfect Matrix Multiplication Tutorial Program in a C# 5.0 Console Application
  • Multiply any number of rows with any number of columns
  • Check for Matrices with invalid rows and Columns
  • Ask for entry of valid Matrix elements if value entered is invalid
  • All work done in .Net Framework 4.5
  • The code has a main class which consists of 3 functions logically structured
  • The first function reads valid elements in the Matrix Arrays
  • The second function multiplies matrices with the help of for loop
  • The third function simply displays the resultant Matrix
  • Check for the source code at the end. 


The Function ReadMatrix() basically reads the values of all elements of the two matrices that are to be multiplied. Also, prior to reading, the matrices are defined with their number of rows and columns. Note that to multiply two matrices we need the number of columns of first matrix to be equal to the number of rows of second matrix. So, when we multiply Mat A x Mat B, number of columns in A should be equal to number of rows in B. Also note that A x B is not equal to B x A.  

public void ReadMatrix()
        {
            Console.WriteLine("****************************************************");
            Console.WriteLine("*********http://www.code-kings.blogspot.com*********");
            Console.WriteLine("****************************************************\n");


            Console.WriteLine("\nPlease Enter Details of First Matrix");
            Console.Write("\n*Number of Rows in First Matrix : ");
            int m = int.Parse(Console.ReadLine());
            Console.Write("\n*Number of Columns in First Matrix : ");
            int n = int.Parse(Console.ReadLine());
            a = new int[m, n];
            Console.WriteLine("\n*Enter the elements of First Matrix : ");
            for (int i = 0; i < a.GetLength(0); i++)
            {
                for (int j = 0; j < a.GetLength(1); j++)
                {
                    try
                    {
                        Console.WriteLine("Enter Element " + (1 + i).ToString() + " " + (1 + j).ToString());
                        a[i, j] = int.Parse(Console.ReadLine());
                        Console.WriteLine("     Value Accepted");
                    }
                    catch
                    {
                        Console.WriteLine("\nPlease Enter a Valid Value(Final Chance)");
                            Console.WriteLine("Enter Element " + (1 + i).ToString() + " " + (1 + j).ToString());
                            a[i, j] = int.Parse(Console.ReadLine());
                            Console.WriteLine("     Value Accepted");
                        
                    }
                }
            }



            Console.WriteLine("\nPlease Enter Details of Second Matrix");
            Console.Write("\n**Number of Rows in Second Matrix :");
            m = int.Parse(Console.ReadLine());
            Console.Write("\n**Number of Columns in Second Matrix :");
            n = int.Parse(Console.ReadLine());
            b = new int[m, n];
            Console.WriteLine("\n**Please Enter Elements of Second Matrix:");
            for (int i = 0; i < b.GetLength(0); i++)
            {
                for (int j = 0; j < b.GetLength(1); j++)
                {
                    try
                    {
                        Console.WriteLine("Enter Element " + (1 + i).ToString() + " " + (1 + j).ToString());
                        b[i, j] = int.Parse(Console.ReadLine());
                        Console.WriteLine("     Value Accepted");
                    }
                    catch
                    {
                        Console.WriteLine("\nPlease Enter a Valid Value(Final Chance)");
                            b[i, j] = int.Parse(Console.ReadLine());
                            Console.WriteLine("     Value Accepted");
                        
                    }
                }
            }
        }

The function to print the first and second matrix followed by the resultant matrix is shown below. A for loop embedded in another for loop does this job very well. The first for loop works for the row number while the second for loop works for the column number. 


        public void PrintMatrix()
        {
            Console.WriteLine("\nFirst Matrix:");
            for (int i = 0; i < a.GetLength(0); i++)
            {
                for (int j = 0; j < a.GetLength(1); j++)
                {
                    Console.Write("\t" + a[i, j]);
                }
                Console.WriteLine();
            }

            Console.WriteLine("\n Second Matrix:");
            for (int i = 0; i < b.GetLength(0); i++)
            {
                for (int j = 0; j < b.GetLength(1); j++)
                {
                    Console.Write("\t" + b[i, j]);
                }
                Console.WriteLine();
            }


            Console.WriteLine("\n Resultant Matrix by Multiplying First & Second Matrix");
            for (int i = 0; i < c.GetLength(0); i++)
            {
                for (int j = 0; j < c.GetLength(1); j++)
                {
                    Console.Write("\t" + c[i, j]);
                }
                Console.WriteLine();
            }


            Console.WriteLine("Do You Want To Multiply Once Again (Y/N)");

            if (Console.ReadLine().ToString() == "y" || Console.ReadLine().ToString() == "Y" || Console.ReadKey().ToString() == "y" || Console.ReadKey().ToString() == "Y")
            {
                MatrixMultiplication mm = new MatrixMultiplication();
                mm.ReadMatrix();
                mm.MultiplyMatrix();
                mm.PrintMatrix();
            }
            else
            {
                Console.WriteLine("\nMatrix Multiplication\n");
                Console.ReadKey();
                Environment.Exit(-1);
            }
        }



A row of the first Matrix and Column of the second Matrix are taken. The corresponding terms are multiplied and added together. They are stored in a location(Matrix C) that is specified by the Row Number of Matrix A and Column Number of Matrix B. The simplest way to do this in your code is by adding a total of 3 for loops. The first two loops simulate the Row Number and Column Number. The third for loop adds the three multiplied pair elements together and stores their result in the C Matrix. Watch the code below:


        public void MultiplyMatrix()
        {
            if (a.GetLength(1) == b.GetLength(0))
            {
                c = new int[a.GetLength(0), b.GetLength(1)];
                for (int i = 0; i < c.GetLength(0); i++)
                {
                    for (int j = 0; j < c.GetLength(1); j++)
                    {
                        c[i, j] = 0;
                        for (int k = 0; k < a.GetLength(1); k++) // OR k<b.GetLength(0)
                            c[i, j] = c[i, j] + a[i, k] * b[k, j];
                    }
                }
            }
            else
            {
                Console.WriteLine("\n Number of columns in First Matrix should be equal to Number of rows in Second Matrix.");
                Console.WriteLine("\n Please re-enter correct dimensions.");
                Environment.Exit(-1);
            }
        }


Please Note:
** Do not Copy & Paste code written here ; instead type it in your Development Environment
** Testing done in .Net Framework 4.5 but code should be very similar for previous versions of .Net
** All Program Codes written here are 100%  tested & running.

Custom Search