Advertisement
SvetoslavUzunov

Matrix multiplication with methods

Apr 1st, 2021
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.55 KB | None | 0 0
  1. using System;
  2.  
  3. namespace PracticeExams
  4. {
  5.     class Program
  6.     {
  7.         static void Main()
  8.         {
  9.             int[,] matrixA = {
  10.                 {1, 2, 3 },
  11.                 {4, 5, 6 },
  12.                 {7, 8, 9 }
  13.             };
  14.  
  15.             int[,] matrixB = {
  16.                 {9, 8, 7 },
  17.                 {6, 5, 4 },
  18.                 {3, 2, 1 }
  19.             };
  20.  
  21.             if (matrixA.GetLength(0) != matrixB.GetLength(1)) Console.WriteLine("Error!");
  22.             else MultiplicationsMatrix(matrixA, matrixB);
  23.         }
  24.  
  25.         static void MultiplicationsMatrix(int[,] matrixA, int[,] matrixB)
  26.         {
  27.             int[,] matrixC = new int[matrixA.GetLength(0), matrixB.GetLength(1)];
  28.  
  29.             for (int row = 0; row < matrixA.GetLength(0); row++)
  30.             {
  31.                 for (int col = 0; col < matrixB.GetLength(1); col++)
  32.                 {
  33.                     matrixC[row, col] = 0;
  34.                     for (int k = 0; k < matrixC.GetLength(0); k++)
  35.                     {
  36.                         matrixC[row, col] += matrixA[row, k] * matrixB[k, col];
  37.                     }
  38.                 }
  39.             }
  40.             PrintMatrix(matrixC);
  41.         }
  42.  
  43.         static void PrintMatrix(int[,] matrixC)
  44.         {
  45.             for (int row = 0; row < matrixC.GetLength(0); row++)
  46.             {
  47.                 for (int col = 0; col < matrixC.GetLength(1); col++)
  48.                 {
  49.                     Console.Write(matrixC[row, col] + " ");
  50.                 }
  51.                 Console.WriteLine();
  52.             }
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement