Scalar matrix program in java

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

Scalar Matrix : A square matrix is said to be scalar matrix if all the main diagonal elements are equal and other elements except main diagonal are zero. Scalar matrix can also be written in form of n * I, where n is any real number and I is the identity matrix.

import java.util.*;
class ScalarMatrix
{
	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 :("+i+","+j+") ");
				A[i][j]=sc.nextInt();
			}
		}

		/* Printing the matrix */
		
		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();
		}
		
		
		int p = 0, q = 0, x = A[0][0]; // 'x' is storing the 1st main diagonal element
		
		for(int i=0;i<m;i++)
		{
			for(int j=0;j<m;j++)
			{
			    /* Checking that the matrix is diagonal or not */
				if(i!=j && A[i][j]!=0) // All non-diagonal elements must be zero
				{
					p=1;
					break;
				}
				/* Checking the matrix for scalarity */
				// All main diagonal elements must be equal to 'x' and non-zero
				if(i==j && (A[i][j]==0 || A[i][j]!=x)) 
				{
					q=1;
					break;
				}
		    }
		}
		
		if(p==0 && q==0)
			System.out.println("The matrix is scalar");
		else
			System.out.println("The matrix is not scalar");
	}
}

Output:

Enter the size of the matrix : 3
Enter an element :(0,0) 1
Enter an element :(0,1) 2
Enter an element :(0,2) 1
Enter an element :(1,0) 3
Enter an element :(1,1) 1
Enter an element :(1,2) 3
Enter an element :(2,0) 1
Enter an element :(2,1) 1
Enter an element :(2,2) 3
The Matrix is :
1 2 1
3 1 3
1 1 3
The matrix is not scalar
Enter the size of the matrix : 3
Enter an element :(0,0) 1
Enter an element :(0,1) 0
Enter an element :(0,2) 0
Enter an element :(1,0) 0
Enter an element :(1,1) 1
Enter an element :(1,2) 0
Enter an element :(2,0) 0
Enter an element :(2,1) 0
Enter an element :(2,2) 1
The Matrix is :
1 0 0
0 1 0
0 0 1
The matrix is scalar

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.