C Program to Check Diagonal Matrix

Check Diagonal Matrix
Diagonal Matrix

A diagonal matrix is a square matrix in which all the elements outside the main diagonal are zero. In other words, only the elements along the main diagonal (from the top-left to the bottom-right) can be non-zero.

This program checks if a given matrix is a diagonal matrix by verifying that all off-diagonal elements are zero.



Code


#include <stdio.h>

int isDiagonalMatrix(int matrix[][10], int n) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            // Check if the element is off-diagonal and non-zero
            if (i != j && matrix[i][j] != 0) {
                return 0;  // Not a diagonal matrix
            }
        }
    }
    return 1;  // It is a diagonal matrix
}

int main() {
    int n;
    int matrix[10][10];

    printf("Enter the order of the matrix (n x n): ");
    scanf("%d", &n);

    printf("Enter the elements of the matrix:\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }

    if (isDiagonalMatrix(matrix, n)) {
        printf("The matrix is a diagonal matrix.\n");
    } else {
        printf("The matrix is not a diagonal matrix.\n");
    }

    return 0;
}
    


Output

Example 1:

Enter the order of the matrix (n x n): 3
Enter the elements of the matrix:
5 0 0
0 8 0
0 0 3
The matrix is a diagonal matrix.

Example 2:

Enter the order of the matrix (n x n): 3
Enter the elements of the matrix:
5 0 2
0 8 0
0 0 3
The matrix is not a diagonal matrix.


Explanation

  • Input: The user inputs the order of the matrix, n, followed by n x n elements.
  • Function isDiagonalMatrix: This function iterates through each element in the matrix, checking if any off-diagonal element (where i != j) is non-zero. If found, it immediately returns 0, indicating the matrix is not a diagonal matrix. If no such element exists, it returns 1, confirming the matrix is diagonal.
  • Result: Based on the function's return value, the program prints whether the matrix is a diagonal matrix or not.