Problem: Write a C program to check whether the given matrix is an identity matrix or not.
In linear algebra, the identity matrix (sometimes ambiguously called a unit matrix) of size n is the n × n square matrix with ones on the main diagonal and zeros elsewhere.

Steps to check identity matrix in C:
- Input a matrix.
- Iterate through the elements of the matrix:
- For
i==j
check ifmatrix[i][i] != 1
and fori!=j
check ifmatrix[i][j] != 0
:- If any element satisfies any of the above conditions then the input matrix is not an identity matrix.
- For
- Otherwise, the matrix is an identity matrix.
Here is the implementation of the steps in C:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #include <stdio.h> #include <stdbool.h> int main() { //Flag to decide whether matrix is identity or not bool flag =true; //order of the matrix const int n=3; //Input matrix int matrix[n][n] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; //Iterate through the left diagonal elements for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ //left diagonal element should be 1 if(i==j && matrix[i][j] != 1){ flag = false; break; } //non diagonal element should be 0 else if(i!=j &&matrix[i][j] != 0){ flag = false; break; } } } if(flag==true) printf("Identity Matrix \n"); else printf("Not an Identity Matrix \n"); return 0; } |
Output:
Identity MatrixIn the program, we have used a 2D array to represent the matrix and for loops to iterate through the matrix elements.
In this programming example, we learned to check the identity matrix in C using the ‘for’ loop and ‘if’ condition.