# C Program: Generate an Identity Matrix

An identity matrix (also known as a unit matrix) is an n x n square matrix where the elements along the diagonal are all ones and the rest are zero.

An identity matrix is usually denoted by $I_{n}$ or sometimes just $I$.

Since we are to generate a square matrix, where the number of rows equals the number of columns, we make use of just one scanf() to accept either dimension in our C program below. Also we make use of two for loops to generate the identity matrix: the first to loop over rows and the the second to loop over columns. When the $i$-th row equals the $j$-th column we print 1, else we print 0.

				
#include <stdio.h>

int main() {
unsigned short i, j, n;

printf("Enter the dimension of the matrix: ");
scanf("%hu", &n);

for(i = 0; i < n;i++) {
for(j = 0; j < n;j++) {
if(i == j) {
printf("1 ");
} else {
printf("0 ");
}
}
printf("\n");
}

return 0;
}