Home »
.Net »
C# Programs
C# | Check Identity Matrix
Here, we are going to learn how to check the matrix is an identity matrix or not in C#?
Submitted by Nidhi, on November 02, 2020 [Last updated : March 19, 2023]
Here, we will read a matrix from the user and then check the input matrix is an identity matrix or not.
C# program to check the matrix is an identity matrix or not
The source code to check the matrix is an identity matrix or not, is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# | Check Identity Matrix.
using System;
class MatrixDemo
{
public static void Main(string[] args)
{
int i = 0;
int j = 0;
int order = 0;
int isIdentity = 0;
int[,] Matrix= new int[5, 5];
Console.Write("Enter the order for matrix: ");
order = int.Parse(Console.ReadLine());
Console.Write("Enter the elements of matrix: ");
for (i = 0; i < order; i++)
{
for (j = 0; j < order; j++)
{
Matrix[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("\nMatrix: ");
for (i = 0; i < order; i++)
{
for (j = 0; j < order; j++)
{
Console.Write(Matrix[i, j] + "\t");
}
Console.WriteLine();
}
for (i = 0; i < order; i++)
{
for (j = 0; j < order; j++)
{
if ((i == j && Matrix[i, j] != 1) || (i != j && Matrix[i, j] != 0))
{
isIdentity = 1;
break;
}
}
}
if(isIdentity==1)
Console.WriteLine("Matrix is not an identity matrix");
else
Console.WriteLine("Matrix is an identity matrix");
}
}
Output
Enter the order for matrix: 2
Enter the elements of matrix: 1
0
0
1
Matrix:
1 0
0 1
Matrix is an identity matrix
Press any key to continue . . .
Explanation
In the above program, we created a class MatrixDemo that contains a Main() method. The Main() method is the entry point for the program, Here, we created a 2-D array to represent a matrix. Then read the order for matrix.
Console.Write("Enter the elements of matrix: ");
for (i = 0; i < order; i++)
{
for (j = 0; j < order; j++)
{
Matrix[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("\nMatrix: ");
for (i = 0; i < order; i++)
{
for (j = 0; j < order; j++)
{
Console.Write(Matrix[i, j] + "\t");
}
Console.WriteLine();
}
Here, we read the elements of the matrix from the user and then printed the matrix on the console screen.
for (i = 0; i < order; i++)
{
for (j = 0; j < order; j++)
{
if ((i == j && Matrix[i, j] != 1) || (i != j && Matrix[i, j] != 0))
{
isIdentity = 1;
break;
}
}
}
if(isIdentity==1)
Console.WriteLine("Matrix is not an identity matrix");
else
Console.WriteLine("Matrix is an identity matrix");
In the above code, we wrote code to check the input matrix is an identity matrix or not. If the value of the "isIdentity" variable is assigned to 1, it means the input matrix is not an identity matrix.
C# Basic Programs »