C# program to add two matrices has been shown here. Two matrices $[A]_{m \times n}$ and $[B]_{p \times q}$ are considered for subtraction if the number of rows and columns are same in both of the matrices i.e. $m = p$ and $n = q$.

#### Page content(s):

1. Program & Output: Iterative approach

1. Algorithm

2. Pseudocode

3. Time Complexity

## 1. C# Program for matrix subtraction

Code has been copied
/* *******************************************
alphabetacoder.com
C# program for matrix subtraction
******************************************* */

using System;

namespace MatrixSubtraction
{
class Program
{
static void Main(string[] args)
{
//declare and initialize variable
int m, n, p, q, i, j;
int[, ] A = new int[10, 10];
int[, ] B = new int[10, 10];

//take input of the order of first matrix
Console.WriteLine("Enter the number of row and column of first matrix=");

//take input of the first matrix
Console.WriteLine("Enter the elements of first matrix of order " + m + " x " + n +" = ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
}
}

//show the first matrix
Console.WriteLine("First input matrix:");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(A[i, j]+" ");
}
Console.WriteLine(" ");
}

//take input of the order of second matrix
Console.WriteLine("Enter the number of row and column of second matrix=");

//take input of the second matrix
Console.WriteLine("Enter the elements of second matrix of order " + p + " x " + q + " = ");
for (i = 0; i < p; i++)
{
for (j = 0; j < q; j++)
{
}
}

//show the second matrix
Console.WriteLine("Second input matrix:");
for (i = 0; i < p; i++)
{
for (j = 0; j < q; j++)
{
Console.Write(B[i, j]+" ");
}
Console.WriteLine(" ");
}

// check if order of matrices are same
// if not same then subtraction is not possible
if (m != p || n != q)
{
Console.WriteLine("\nMatrices are of different order, hence subtraction is not possible");
}
else
{
//Do subtraction
Console.WriteLine("Resultant matrix after subtraction: ");
for (i = 0; i < p; i++)
{
for (j = 0; j < q; j++)
{
Console.Write(A[i, j] - B[i, j]+" ");
}
Console.WriteLine(" ");
}
}

// wait for user to press any key
}
}
}


Output

#### Case 1:

Enter the number of row and column of first matrix=

2

2

Enter the elements of first matrix of order 2 x 2 =

1

2

3

4

First input matrix:

1 2

3 4

Enter the number of row and column of second matrix=

2

2

Enter the elements of second matrix of order 2 x 2 =

2

3

5

1

Second input matrix:

2 3

5 1

Resultant matrix after subtraction:

-1 -1

-2 3

#### Case 2:

Enter the number of row and column of first matrix=

2

3

Enter the elements of first matrix of order 2 x 3 =

1

2

3

4

5

6

First input matrix:

1 2 3

4 5 6

Enter the number of row and column of second matrix=

2

2

Enter the elements of second matrix of order 2 x 2 =

2

3

5

1

Second input matrix:

2 3

5 1

Matrices are of different order, hence subtraction is not possible