Write a program that checks whether a matric is an Identity matrix.
Identity matrix is a square matrix whose main diagonal elements is equal to 1 and other elements are 0.
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
#define SIZE 50
void main()
{
int A[SIZE][SIZE];
int dim; /* dimensions */
int I, J, aux;
do {
printf("Number of rows/columns (max.%d) : ", SIZE);
scanf("%d", &dim);
} while (dim <= 0 || dim > SIZE);
printf("*** Matrix ***\n");
for (I = 0; I<dim; I++)
for (J = 0; J<dim; J++)
{
printf("A[%d][%d] : ", I, J);
scanf("%d", &A[I][J]);
}
printf(" Matrix \n");
for (I = 0; I<dim; I++)
{
for (J = 0; J<dim; J++)
printf("%6d", A[I][J]);
printf("\n");
}
// we loop over the rows
for (I = 0; I<dim; I++)
{
for (J = 0; J<dim; J++)
{
if(I==J && A[I][J] !=1)
break;
if(I!=J && A[I][J] !=0)
break;
}
if(J<dim)
break;
}
if(I==dim)
printf(" Identity matrix \n");
else
printf(" NOT Identity matrix \n");
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sorting by propagation (bubble sort)