C++ Online Compiler
Example: Check if a given Matrix is an Identity Matrix in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Check if a given Matrix is an Identity Matrix #include <iostream> #include <vector> // Using std::vector for dynamic matrices using namespace std; // Function to check if a matrix is an identity matrix bool isIdentityMatrix(const vector<vector<int>>& matrix) { int rows = matrix.size(); if (rows == 0) { // Empty matrix is not an identity matrix return false; } int cols = matrix[0].size(); // 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 the matrix elements for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { // Step 3: Check diagonal elements if (i == j) { if (matrix[i][j] != 1) { return false; // Diagonal element is not 1 } } // Step 4: Check non-diagonal elements else { 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() { // Example 1: Identity Matrix vector<vector<int>> matrix1 = { {1, 0, 0}, {0, 1, 0}, {0, 0, 1} }; cout << "Matrix 1 is " << (isIdentityMatrix(matrix1) ? "an Identity Matrix" : "NOT an Identity Matrix") << endl; // Example 2: Not an Identity Matrix (off-diagonal not zero) vector<vector<int>> matrix2 = { {1, 2, 0}, {0, 1, 0}, {0, 0, 1} }; cout << "Matrix 2 is " << (isIdentityMatrix(matrix2) ? "an Identity Matrix" : "NOT an Identity Matrix") << endl; // Example 3: Not an Identity Matrix (diagonal not one) vector<vector<int>> matrix3 = { {1, 0, 0}, {0, 5, 0}, {0, 0, 1} }; cout << "Matrix 3 is " << (isIdentityMatrix(matrix3) ? "an Identity Matrix" : "NOT an Identity Matrix") << endl; // Example 4: Not an Identity Matrix (not square) vector<vector<int>> matrix4 = { {1, 0}, {0, 1}, {0, 0} }; cout << "Matrix 4 is " << (isIdentityMatrix(matrix4) ? "an Identity Matrix" : "NOT an Identity Matrix") << endl; // Example 5: Not an Identity Matrix (empty matrix) vector<vector<int>> matrix5; cout << "Matrix 5 is " << (isIdentityMatrix(matrix5) ? "an Identity Matrix" : "NOT an Identity Matrix") << endl; // Example 6: 1x1 Identity Matrix vector<vector<int>> matrix6 = {{1}}; cout << "Matrix 6 is " << (isIdentityMatrix(matrix6) ? "an Identity Matrix" : "NOT an Identity Matrix") << endl; return 0; }
Output
Clear
ADVERTISEMENTS