Categories
Class 11 Class 12

Scalar Matrix in Java

Write a program to input a 2-dimensional square matrix and check whether it is a scalar matrix or not.

A scalar matrix is a square matrix in which the main diagonal (left diagonal) entries are all equal.

Example:
INPUT:
Dimension: 4
Elements:

5 0 0 0
0 5 0 0
0 0 5 0
0 0 0 5

OUTPUT:
The matrix is scalar.

Program:

import java.io.*;
class Scalar{
    public static void main(String args[])
    throws IOException{
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.print("Dimension: ");
        int n = Integer.parseInt(br.readLine());
        int m[][] = new int[n][n];
        System.out.println("Enter matrix elements:");
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                m[i][j] = Integer.parseInt(br.readLine());
            }
        }
        boolean status = true;
        int value = m[0][0];
        for(int i = 1; i < n; i++){
            if(value != m[i][i]){
                status = false;
                break;
            }
        }
        if(status)
            System.out.println("The matrix is scalar.");
        else
            System.out.println("The matrix is not scalar.");
    }
}

Leave a Reply