Q:

C program to check a given matrix is an identity matrix or not

0

C program to check a given matrix is an identity matrix or not

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

The identity matrix of size n is the n x n square matrix with ones on the main diagonal and zeros elsewhere.

Given a matrix, we have to check whether the matrix is an identity matrix or not using C program.

Program:

The source code to check a given matrix is an identity matrix or not is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to check a given matrix is an identity matrix or not

#include <stdio.h>

int isIdentityMatrix(int Matrix[][3])
{
    int flag = 0;
    int i, j;

    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            if (i == j && Matrix[i][j] != 1) {
                flag = -1;
                break;
            }
            else if (i != j && Matrix[i][j] != 0) {
                flag = -1;
                break;
            }
        }
    }

    return flag;
}
int main(void)
{
    int Matrix1[3][3] = {
        { 1, 0, 0 },
        { 0, 1, 0 },
        { 0, 0, 1 }
    };

    int Matrix2[3][3] = {
        { 1, 0, 0 },
        { 0, 1, 1 },
        { 0, 0, 1 }
    };

    if (isIdentityMatrix(Matrix1) == 0)
        printf("Matrix1 is an IDENTITY MATRIX\n");
    else
        printf("Matrix1 is NOT an identity matrix\n");

    if (isIdentityMatrix(Matrix2) == 0)
        printf("Matrix2 is an IDENTITY MATRIX\n");
    else
        printf("Matrix2 is NOT an identity matrix\n");

    return 0;
}

Output:

Matrix1 is an IDENTITY MATRIX
Matrix2 is NOT an identity matrix

Explanation:

In the above program, we created two functions isIdentityMatrix() and main() function. The isIdentityMatrix() function is a user defined function, it is used to check a matrix is identity matrix or not.

In the main() function, we created two matrices Matrix1Matrix2. Then we checked matrices are identity matrices or not using the isIdentityMatrix() function and then we printed the appropriate message on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C program to check a given matrix is a sparse matr... >>
<< C program to check two matrices are identical or n...