2D Array – Scalar Matrix

Write a program to enter elements in the matrix of 4 into 4 order and check whether the matrix is scalar matrix or not( the scalar matrix is basically a square Matrix, whose all off diagonal elements are 0 and on diagonal elements are equal)

Scalar Matrix example
import java.util.Scanner;
class TwoDArray
{
    public static void main(String[] args) 
    {
        Scanner in = new Scanner(System.in);
        int n = 4;
        
        int a[][] = new int[n][n];
        //Input the 2-D Array
        System.out.println("Enter all the elements of matrix:");
        for (int i = 0; i < n; i++) 
        {
            for (int j = 0; j < n; j++) 
            {
                a[i][j] = in.nextInt();
            }
        }
        
        //Print the Original 2D Array
        System.out.println("Original Matrix:");
        for (int i = 0; i < n; i++) 
        {
            for (int j = 0; j < n; j++) 
            {
                System.out.print(a[i][j] + " ");
            }
            System.out.println("");
        }
        
        int flag = 1; //initially think it is a scalar matrix
        int x = a[0][0];
        //Checking scalar matrix
        for (int i = 0; i < n; i++) 
        {
            for (int j = 0; j < n; j++) 
            {
                if(i == j) // condition for left diagonal
                {
                    if(a[i][j]!=x) // if any element is different
                    {
                        flag = 0;
                        break;
                    }
                }
                else // for non-diagonal elements
                {
                    if(a[i][j]!=0) // if it is not 0
                    {
                        flag = 0;
                        break;
                    }
                }
            }
        }
        
        if(flag == 1)
            System.out.println("It is a Scalar Matrix");
        else
            System.out.println("It is not a Scalar Matrix");
    }
}

OUTPUT

Enter all the elements of matrix:
1
0
0
0
0
1
0
0
0
0
1
0
0
0
0
1

Original Matrix:
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

It is a Scalar Matrix

Leave a Comment

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