C# Sharp Exercises: Check whether a given matrix is an Identity Matrix
C# Sharp Array: Exercise-31 with Solution
Write a program in C# Sharp to check whether a given matrix is an Identity Matrix.
Sample Solution:-
C# Sharp Code:
//In a square matrix if all the main diagonal elements are 1's and
//all the remaining elements are 0's is called an Identity Matrix.
using System;
class Exercise31
{
public static void Main()
{
int[,] arr1 = new int[50,50];
int i, j, r1,c1;
Console.Write("\n\n Check whether a given matrix is an Identity Matrix :\n ");
Console.Write("-----------------------------------------------------------\n");
Console.Write(" Input the orders(2x2, 3x3, ...) of square matrix : ");
r1 = Convert.ToInt32(Console.ReadLine());
c1=r1;
Console.Write(" Input elements in the matrix :\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
Console.Write(" element - [{0}],[{1}] : ",i,j);
arr1[i,j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.Write(" The matrix is :\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1 ;j++)
Console.Write(" {0} ",arr1[i,j]);
Console.Write("\n");
}
for (i = 0; i < r1; i++)
{
for (j = 0; j < c1; j++)
{
if ((i == j && arr1[i, j] != 1) || (i != j && arr1[i, j] != 0))
{
goto label;
}
}
}
Console.WriteLine(" The matrix is an Identity Matrix.\n\n");
return;
label:
Console.WriteLine("\n The matrix is not an Identity Matrix\n\n");
}
}
Sample Output:
Check whether a given matrix is an Identity Matrix : ----------------------------------------------------------- Input the orders(2x2, 3x3, ...) of square matrix : 2 Input elements in the matrix : element - [0],[0] : 1 element - [0],[1] : 0 element - [1],[0] : 0 element - [1],[1] : 1 The matrix is : 1 0 0 1 The matrix is an Identity Matrix
Flowchart:
C# Sharp Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a program in C# Sharp to accept two matrices and check whether they are equal.
Next: Write a C# Sharp program to get only the odd values from a given array of integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework