Write a program in java to input a 2D matrix and check it whether it is scalar or not. The matrix is : 5 0 0 0 0 5 0 0 0 0 5 0 0 0 0 5

Write a program in java to input a 2D matrix and check it whether it is scalar or not. The matrix is : 

5 0 0 0

0 5 0 0 

0 0 5 0 

0 0 0 5

Answers:

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.");
 }
}

Output:




Post a Comment

0 Comments