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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Hemant SrivastavaPosted Nov 12, 2013, 11:03 AM
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();
}
}
}
Priyank KharePosted Nov 12, 2013, 5:39 AM
Following is the program to verify whether a given matrix is identity or not :-