**Question:**

Write a Program in Java to input a 2-D square matrix and check whether it is a Diagonal Matrix or not.

**Diagonal Matrix :** A diagonal matrix is a matrix (usually a square matrix) in which the entries outside the main diagonal (↘) are all zero. The diagonal entries themselves may or may not be zero (but all diagonal entries cannot be zero).

**Example:**

**Solution:**

/** * The class DiagonalMatrix inputs a Matrix and checks whether it is a diagonal matrix or not * @author : www.guideforschool.com * @Program Type : BlueJ Program - Java */ import java.util.*; class DiagonalMatrix { public static void main(String args[])throws Exception { Scanner sc=new Scanner(System.in); System.out.print("Enter the size of the matrix : "); int m=sc.nextInt(); int A[][]=new int[m][m]; /* Inputting the matrix */ for(int i=0;i<m;i++) { for(int j=0;j<m;j++) { System.out.print("Enter an element : "); A[i][j]=sc.nextInt(); } } /* Printing the matrix */ System.out.println("*************************"); System.out.println("The Matrix is : "); for(int i=0;i<m;i++) { for(int j=0;j<m;j++) { System.out.print(A[i][j]+"\t"); } System.out.println(); } System.out.println("*************************"); int p=0, q=0; for(int i=0;i<m;i++) { for(int j=0;j<m;j++) { if(i!=j && A[i][j]!=0) // Checking non-diagonal elements { p=1; break; } if(i==j && A[i][j]==0) // Checking diagonal elements { q++; } } } if(p==0 && q<m) System.out.println("The matrix is Diagonal"); else System.out.println("The matrix is not Diagonal"); } }

**Output:**

Enter the size of the matrix : 4

Enter an element : 5

Enter an element : 0

Enter an element : 0

Enter an element : 0

Enter an element : 0

Enter an element : 1

Enter an element : 0

Enter an element : 0

Enter an element : 0

Enter an element : 0

Enter an element : 0

Enter an element : 0

Enter an element : 0

Enter an element : 0

Enter an element : 0

Enter an element : 7

*************************

The Matrix is :

5 0 0 0

0 1 0 0

0 0 0 0

0 0 0 7

*************************

The matrix is Diagonal

System.out.print(*****************). What is this

A style statement 🙂

It is really good program. Coding is nicely done. Thanks