C PROGRAMMING PROGRAM • MATRICES

Check Whether a Matrix Is an Identity Matrix

Learn how to check whether a matrix is an identity matrix using a clear C program.

IntermediateSquare matrixIdentity matrixCondition

PROBLEM UNDERSTANDING

Input and expected output

Sample input
3
1 0 0
0 1 0
0 0 1
Sample output
Identity matrix

COMPLETE C PROGRAM

Complete C implementation

identity-matrix-check.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int size, matrix[10][10], identity = 1;

    scanf("%d", &size);
    if (size < 1 || size > 10) return 1;
    for (int row = 0; row < size; row++)
        for (int column = 0; column < size; column++) scanf("%d", &matrix[row][column]);
    for (int row = 0; row < size && identity; row++) {
        for (int column = 0; column < size; column++) {
            int expected = row == column ? 1 : 0;
            if (matrix[row][column] != expected) { identity = 0; break; }
        }
    }
    printf(identity ? "Identity matrix\n" : "Not an identity matrix\n");
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Identity matrix
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Require ones on the main diagonal and zeros in every other position.
  3. Display the computed result.

Require ones on the main diagonal and zeros in every other position.

EFFICIENCY

Time and space complexity

Time complexity

O(rows × columns)

Auxiliary space

O(rows × columns)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.