C Online Compiler
Example: Check if a matrix is an Identity Matrix in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Check if a matrix is an Identity Matrix #include <stdio.h> #include <stdbool.h> // For using boolean type // Function to check if a matrix is an identity matrix bool isIdentityMatrix(int matrix[10][10], int rows, int cols) { // Step 1: Check if the matrix is square if (rows != cols) { return false; // Not a square matrix, so cannot be an identity matrix } // Step 2: Iterate through all elements of the matrix for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { // Step 3: Check diagonal elements if (i == j) { // Current element is on the main diagonal if (matrix[i][j] != 1) { return false; // Diagonal element is not 1 } } else { // Current element is not on the main diagonal // Step 4: Check non-diagonal elements if (matrix[i][j] != 0) { return false; // Non-diagonal element is not 0 } } } } // Step 5: If all checks pass, it's an identity matrix return true; } int main() { int rows1 = 3, cols1 = 3; int matrix1[10][10] = { {1, 0, 0}, {0, 1, 0}, {0, 0, 1} }; printf("Matrix 1:\n"); for (int i = 0; i < rows1; i++) { for (int j = 0; j < cols1; j++) { printf("%d ", matrix1[i][j]); } printf("\n"); } if (isIdentityMatrix(matrix1, rows1, cols1)) { printf("The matrix 1 is an Identity Matrix.\n\n"); } else { printf("The matrix 1 is NOT an Identity Matrix.\n\n"); } int rows2 = 3, cols2 = 3; int matrix2[10][10] = { {1, 0, 0}, {0, 2, 0}, {0, 0, 1} }; printf("Matrix 2:\n"); for (int i = 0; i < rows2; i++) { for (int j = 0; j < cols2; j++) { printf("%d ", matrix2[i][j]); } printf("\n"); } if (isIdentityMatrix(matrix2, rows2, cols2)) { printf("The matrix 2 is an Identity Matrix.\n\n"); } else { printf("The matrix 2 is NOT an Identity Matrix.\n\n"); } int rows3 = 2, cols3 = 3; // Non-square matrix int matrix3[10][10] = { {1, 0, 0}, {0, 1, 0} }; printf("Matrix 3:\n"); for (int i = 0; i < rows3; i++) { for (int j = 0; j < cols3; j++) { printf("%d ", matrix3[i][j]); } printf("\n"); } if (isIdentityMatrix(matrix3, rows3, cols3)) { printf("The matrix 3 is an Identity Matrix.\n\n"); } else { printf("The matrix 3 is NOT an Identity Matrix.\n\n"); } return 0; }
Output
Clear
ADVERTISEMENTS