In this article, you will dd two matrices in C#. For matrix addition, we require two matrices and both the matrices must be a square matrix.
Explanation:
We first take the user input for a number of rows and the number of columns. Then passing rows and columns, we take input for two matrices A & B. Then those matrices are added as shown in the following program. And lastly, the result matrix is displayed.
C# Program for Matrix Addition
Source Code: The program shows the addition of matrices in C# using classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | using System; class MatrixAddition { int n, m; //Input of First Matrix public int[, ] GetMatrixA(int n, int m) { this.n = n; this.m = m; int[, ] matrix = new int[n, m]; Console.WriteLine("Enter A {0} x {1} matrix", n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { var input = Console.ReadLine(); try { matrix[i, j] = int.Parse(input); } catch (System.Exception ex) { Console.WriteLine("Invalid input !!"); } } } return matrix; } //Input of Second Matrix public int[, ] GetMatrixB(int n, int m) { this.n = n; this.m = m; int[, ] matrix = new int[n, m]; Console.WriteLine("Enter B {0} x {1} matrix", n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { var input = Console.ReadLine(); try { matrix[i, j] = int.Parse(input); } catch (System.Exception ex) { Console.WriteLine("Invalid input !!"); } } } return matrix; } //Addition of two Matrices public int[, ] AddMatrix(int[, ] a, int[, ] b) { int[, ] result = new int[n, m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { result[i, j] = a[i, j] + b[i, j]; } } return result; } //Displaying the result public void DisplayMatrix(int[, ] matrix) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { Console.Write(matrix[i, j] + "\t"); } Console.WriteLine(""); } } } class Program { static void Main(string[] s) { MatrixAddition matrix = new MatrixAddition(); int m, n; Console.WriteLine("Enter Number Of Rows And Columns(must be square matrix) : "); m = Convert.ToInt16(Console.ReadLine()); n = Convert.ToInt16(Console.ReadLine()); int[, ] a = matrix.GetMatrixA(m, n); int[, ] b = matrix.GetMatrixB(m, n); Console.WriteLine("Result of A + B:"); matrix.DisplayMatrix(matrix.AddMatrix(a, b)); } } |
Output: