In this tutorial, we will write a C# program to subtract two matrices. For matrix Subtraction, 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 subtracted as shown in the following program. And lastly, the result matrix is displayed.
C# Program for Matrix Subtraction
Source Code: Matrix subtraction in C# using classes.
//Matrix Subtraction
using System;
class MatrixSubtraction
{
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;
}
//Subtraction of two Matrices
public int[, ] SubMatrix(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)
{
MatrixSubtraction matrix = new MatrixSubtraction();
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.SubMatrix(a, b));
}
}
The output of matrix Subtraction in C#.
