Computer Science

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

Scalar Matrix: A scalar matrix is a diagonal matrix where the left diagonal elements are same.

The Matrix is:
5 0 0 0
0 5 0 0
0 0 5 0
0 0 0 5

The Matrix is Scalar

Java

Java Arrays

7 Likes

Answer

import java.util.Scanner;

public class KboatScalarMatrix
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the size of the matrix: ");
        int n = in.nextInt();
        
        int arr[][] = new int[n][n];
        
        System.out.println("Enter elements of the matrix: ");
        for (int i = 0; i < n; i++) {
            System.out.println("Enter Row "+ (i+1) + " :");
            for (int j = 0; j < n; j++) {
                arr[i][j] = in.nextInt();
            }
        }
        
        System.out.println("The Matrix is:");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }
        
        boolean isScalar = true;
        int x = arr[0][0];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if ((i == j && arr[i][j] != x) 
                    || ( i != j && arr[i][j] != 0)) {
                    isScalar = false;
                    break;
                }
            }
            
            if (!isScalar) {
                break;
            }
        }
        
        if (isScalar) {
            System.out.println("The Matrix is Scalar");
        }
        else {
            System.out.println("The Matrix is not Scalar");
        }
    }
}

Output

Answered By

1 Like


Related Questions