Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 27: Write a Java program to determine if the entered matrix is an identity matrix.

Identity.java

import java.util.Scanner;

public class Identity
{
	public static void main(String[] args)
	{
		Scanner s = new Scanner(System.in);
		
		//Input size of the matrix
		//row - number of rows in the matrix.
		//col - number of columns in the matrix.
		
		System.out.println("Enter the number of rows");
		int row = s.nextInt();

		System.out.println("Enter the number of columns");
		int col = s.nextInt();
		
		//Input matrix
		int matrix[][] = new int[row][col];
		boolean flag = true;

		System.out.println("Enter the matrix");
		for(int i=0;i < row;i++)
		{
			for(int j=0;j < col;j++)
			{
				System.out.print("Enter "+i+j+" element: ");
				matrix[i][j] = s.nextInt();
			}
		}
		
		System.out.println("The entered matrix is ");
		for(int i=0; i < row; i++)
		{
			for(int j=0;j < col;j++)
			{
				System.out.print(matrix[i][j]+" ");
			}
			System.out.println();
		}

		if(row!=col)
		{
			System.out.println("Matrix should be a square marix");
		}
		else
		{
			for(int i=0;i < row;i++)
			{
				for(int j=0;j < col;j++)
				{
					if(i==j && matrix[i][j]!=1)
					{
						flag = false;
						break;
					}
					if(i!=j && matrix[i][j]!=0)
					{
						flag = false;
						break;
					}
				}
			}
		
			if(flag == true)
			{
				System.out.println("Given Matrix is an identity matrix");
			}
			else
			{
				System.out.println("Given Matrix is not an identity matrix");
			}
		}
	}
}


If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.