Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program for Identity Matrix in C
Given a square matrix M[r][c] where 'r' is some number of rows and 'c' are columns such that r = c, we have to check that 'M' is identity matrix or not.
Identity Matrix
Identity matrix is also known as Unit matrix of size nxn square matrix where diagonal elements will only have integer value one and non diagonal elements will only have integer value as 0.
Like in the given Example below −
Syntax
int isIdentityMatrix(int matrix[n][n], int n); // Returns 1 if matrix is identity matrix, 0 otherwise
Example 1: Checking Identity Matrix
This program checks if a given matrix is an identity matrix −
#include <stdio.h>
int isIdentityMatrix(int matrix[3][3], int n) {
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (i == j) {
if (matrix[i][j] != 1)
return 0;
} else {
if (matrix[i][j] != 0)
return 0;
}
}
}
return 1;
}
int main() {
int matrix1[3][3] = {{1, 0, 0},
{0, 1, 0},
{0, 0, 1}};
int matrix2[3][3] = {{3, 0, 1},
{6, 2, 0},
{7, 5, 3}};
printf("Matrix 1 is identity matrix: %s<br>",
isIdentityMatrix(matrix1, 3) ? "Yes" : "No");
printf("Matrix 2 is identity matrix: %s<br>",
isIdentityMatrix(matrix2, 3) ? "Yes" : "No");
return 0;
}
Matrix 1 is identity matrix: Yes Matrix 2 is identity matrix: No
Example 2: Creating Identity Matrix
This program creates and displays an identity matrix of given size −
#include <stdio.h>
void createIdentityMatrix(int n) {
int i, j;
printf("Identity Matrix of size %dx%d:<br>", n, n);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (i == j)
printf("1 ");
else
printf("0 ");
}
printf("<br>");
}
}
int main() {
int size = 4;
createIdentityMatrix(size);
return 0;
}
Identity Matrix of size 4x4: 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1
Key Points
- An identity matrix has 1 on the main diagonal (where row index equals column index)
- All other elements are 0
- Identity matrix is always a square matrix (n x n)
- Multiplying any matrix by an identity matrix gives the original matrix
Conclusion
Identity matrices are fundamental in linear algebra. The key property is having ones on the diagonal and zeros elsewhere, making them easy to create and verify programmatically.
Advertisements
