This blog is under construction

Wednesday 24 July 2013

C program to check whether a matrix is diagonal

Write a C program to check whether a matrix is diagonal.


  #include <stdio.h>
  #define MAXROWS 10
  #define MAXCOLS 10

  int main() {
        int i, j, row, col, flag = 0;
        int matrix[MAXROWS][MAXCOLS];

        /* get the number of rows from the user */
        printf("Enter the number of rows:");
        scanf("%d", &row);

        /* get the number of columns from the user */
        printf("Enter the number of columns:");
        scanf("%d", &col);

        /* Boundary Check */
        if (row > MAXROWS || row < 0 || col > MAXCOLS || col < 0) {
                printf("Boundary Level Exceeded!!\n");
                return 0;
        }

        /* get the entries for the input matrix */
        printf("\nEnter the matrix entries:\n");
        for (i = 0; i < row; i++) {
                for (j = 0; j < col; j++) {
                        scanf("%d", &matrix[i][j]);
                }
        }
        /* checking for diagonal matrix */
        for (i = 0; i < row; i++) {
                for (j = 0; j < col; j++) {
                        if (i != j && matrix[i][j] != 0) {
                                flag = 1;
                                goto end;
                        }
                }
        }

  end:
        /* printing the result */
        if (flag) {
                printf("Given Matrix is not a diagonal matrix!!\n");
        } else {
                printf("Given Matrix is a diagonal matrix!!\n");
        }

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of rows:3
  Enter the number of columns:3

  Enter the matrix entries:
  10 00 00
  00 10 00
  00 00 11
  Given Matrix is a diagonal matrix!!


2 comments:

  1. mat[i][j]==0 in that if statement since diagonal matrix means all the elements except diagonal elements are equal to zero

    ReplyDelete
    Replies
    1. Exactly! I was wondering About That ! All The Elements Other Than The Diagonal Elements Are Zeroes

      Delete