VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-print-identity-matrix/

⇱ Program to check Identity Matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to check Identity Matrix

Last Updated : 23 Dec, 2024

Given a square matrix mat[][] of order n*n, the task is to check if it is an Identity Matrix.

Identity Matrix: A square matrix is said to be an identity matrix if the elements of maindiagonal are one and all other elements are zero. The identity Matrix is also known as the Unit Matrix.

👁 Program-for-Identity-Matrix


Examples:

Input: mat[][] = [[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]]

Output: True
Explanation: Main Diagonal = [1, 1, 1, 1], elements of main diagonal are one and all other elements are zero.

Input: mat[][] = [[6, 10, 12, 0],
[0, 5, 0, 0],
[0, 0, 9, 0],
[0, 0, 0, 1]]

Output: False
Explanation: Main Diagonal = [6, 5, 9, 1], elements of main diagonal are not one.

Approach:

The row and column indexes of Primary or Major diagonal are same i.e. lets say mat[][] is matrix then mat[i][i] will be a Major Diagonal element. The idea is to traverse the matrix and check if main diagonal's elements are one and all other elements are zero.


Output
True

Time Complexity: O(n2)
Auxiliary Space: O(1), as no extra space is used

Comment
Article Tags: