C# Program to Add Two Matrices

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.

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: