Scalar Matrix Program in Java

A scalar matrix is a square matrix in which all the elements in the left diagonal (principal diagonal) are same, and rest of the elements are zero.

Example: A scalar matrix of order 3:
5 0 0
0 5 0
0 0 5

Write a Java program to input the size of the square matrix from the user. Allow the user to fill this matrix with integers. Now check and display whether this matrix is a scalar matrix or not.

import java.util.Scanner;
class ScalarMatrix{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("Matrix size: ");
        int size = Integer.parseInt(in.nextLine());
        int mat[][] = new int[size][size];
        System.out.println("Enter matrix elements:");
        for(int i = 0; i < size; i++){
            for(int j = 0; j < size; j++){
                mat[i][j] = Integer.parseInt(in.nextLine());
            }
        }
        int d = mat[0][0];
        boolean status = true;
        outer:
        for(int i = 0; i < size; i++){
            for(int j = 0; j < size; j++){
                if(i == j && d != mat[i][i]){
                    status = false;
                    break outer;
                }
                else if(i != j && mat[i][j] != 0){
                    status = false;
                    break outer;
                }
            }
        }
        System.out.println("ORIGINAL MATRIX");
        for(int i = 0; i < size; i++){
            for(int j = 0; j < size; j++){
                System.out.print(mat[i][j] + "\t");
            }
            System.out.println();
        }
        if(status)
            System.out.println("Scalar Matrix!");
        else
            System.out.println("Not a Scalar Matrix.");
    }
}

Leave a Reply

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