Here's a C Program to find the given matrix is a unit matrix or not with proper explanation and output. This program uses Break, Multidimensional Arrays, Nested Loops and For Loops.
Note: The unit matrix is a square matrix whose diagonal elements are all 1 and non diagonal elements are 0.
# include <stdio.h> # include <conio.h> void main() { int mat[10][10] ; int i, j, size, flag = 1 ; clrscr() ; printf("Enter size of the square matrix : ") ; scanf("%d", &size) ; printf("\nEnter the elements of the matrix : \n\n") ; for(i = 0 ; i < size ; i++) for(j = 0 ; j < size ; j++) scanf("%d", &mat[i][j]) ; for(i = 0 ; i < size ; i++) { for(j = 0 ; j < size ; j++) { if(i == j) if(mat[i][j] != 1) { flag = 0 ; break; } if(i != j) if(mat[i][j] != 0) { flag = 0 ; break; } } } if(flag == 1) printf("\nThe matrix is an unit matrix") ; else printf("\nThe matrix is not an unit matrix") ; getch() ; }
Output of the above program
Output 1:
Enter size of the square matrix : 3
Enter the elements of the matrix :
1 0 0
0 1 0
0 0 1
The matrix is an unit matrix
Output 2:
Enter size of the square matrix : 3
Enter the elements of the matrix :
1 2 3
4 1 5
6 7 1
The matrix is not an unit matrix
Explanation of above program
In this program, we have a square matrix mat of maximum size 10 x
10. The variables i and j are the loop variables that corresponds to
the row and column of the matrix respectively. The variable size contains the size of the matrix. The variable flag is the indicator that is used to determine whether the matrix is unit matrix or not.
First
the program asks the user to enter the size of the matrix and then
using a nested for loops the matrix is populated. In the next nested for loop the program checks whether the matrix is unit matrix or not. The process is as follows:
Inside nested for loops, we have two IF conditions-
- First IF condition checks diagonal elements i.e. when i == j. If i == j then the program checks whether the value of that diagonal element is 1 or not. If the value is not equal to 1 then the value of flag is set to 0 and using the break statement the loop gets terminated as there is no point in checking the rest of the elements once a value other than 1 is found at diagonal position.
- Second IF condition checks non diagonal elements i.e. when i != j. If i != j then the program checks whether the value of that non diagonal element is 0 or not. If the value is non zero then the value of flag is set to 0 and using the break statement the loop gets terminated as there is no point in checking the rest of the elements once a value other than 0 is found at non diagonal position.
Outside the nested for loop, we check whether the values of flag is 0 or 1. If the value of flag = 1 that means the matrix mat is unit matrix otherwise matrix mat is not unit matrix.