Matrix is identity matrix or not?
write a program to verify whether a given matrix is identity matrix or not?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Priyank Khare154 reputationPosted Nov 12, 2013, 12:39 AM EST
Following is the program to verify whether a given matrix is identity or not :-
Hemant SrivastavaRank #581 · 4.2K reputationPosted Nov 12, 2013, 6:03 AM EST
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
Console.WriteLine("Enter the order: ");
int n = int.Parse(Console.ReadLine());
int[,] a = new int[n, n];
int i, j;
Console.WriteLine("\n Enter the matrix\n");
for (i = 0; i < n; i++)
{
int num = 0;
for (j = 0; j < n; j++)
{
Console.WriteLine("Enter [" + (i+1) + ","+ (j+1) + "] element: " );
if (Int32.TryParse(Console.ReadLine(), out num))
{
a[i, j] = num;
}
}
}
Console.WriteLine("Entered Matrix is as folowing:\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(a[i, j] + "\t");
}
Console.WriteLine();
}
bool IsIdentity = false;
// Iterating all the elements of the given matrix
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
// Each Diagonal element should be 1 and all other elements should be 0
if ((i == j && a[i, j] == 1) || (i != j && a[i, j] == 0))
{
IsIdentity = true;
}
else
{
IsIdentity = false;
break;
}
}
}
// After iterating all elemnts of the matrix, checking the IsIdentity flag
if (IsIdentity == true)
{
Console.WriteLine("\nIt is an Identity Matrix");
}
else
{
Console.WriteLine("\nNot an Identity Matrix");
}
Console.ReadLine();
}
}
}