Thursday , 19 October 2017
Home » Array Related Programs » Java Program to check for Diagonal Matrix

Java Program to check for Diagonal Matrix

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:

\begin{bmatrix} 5 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 7 \end{bmatrix}

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

Check Also

[Question 2] ISC 2017 Computer Practical Paper Solved – Quiz Result

Solution of Program 2 of ISC 2017 Computer Science Paper 2 (Practical) Exam. Java program to input the answers of each participant row-wise and calculate their marks

4 comments

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

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

Leave a Reply to Khurshid Md Anwar Cancel reply

Your email address will not be published. Required fields are marked *